brave.propagation.ThreadLocalCurrentTraceContext Java Examples

The following examples show how to use brave.propagation.ThreadLocalCurrentTraceContext. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TraceFilterTests.java    From spring-cloud-sleuth with Apache License 2.0 6 votes vote down vote up
@Test
public void createsChildFromHeadersWhenJoinUnsupported() throws Exception {
	Tracing tracing = Tracing.newBuilder()
			.currentTraceContext(ThreadLocalCurrentTraceContext.newBuilder()
					.addScopeDecorator(StrictScopeDecorator.create()).build())
			.addSpanHandler(this.spans).supportsJoin(false).build();
	HttpTracing httpTracing = HttpTracing.create(tracing);
	this.request = builder().header("b3", "0000000000000014-000000000000000a")
			.buildRequest(new MockServletContext());

	TracingFilter.create(httpTracing).doFilter(this.request, this.response,
			this.filterChain);

	then(Tracing.current().tracer().currentSpan()).isNull();
	then(this.spans).hasSize(1);
	then(this.spans.get(0).parentId()).isEqualTo("000000000000000a");
}
 
Example #2
Source File: CatalogTracing.java    From cxf with Apache License 2.0 5 votes vote down vote up
private static HttpTracing createHttpTracing(String serviceName, AsyncReporter<Span> reporter) {
    final Tracing tracing = Tracing
        .newBuilder()
        .localServiceName(serviceName)
        .currentTraceContext(
            ThreadLocalCurrentTraceContext
                .newBuilder()
                .addScopeDecorator(MDCScopeDecorator.create()) 
                .build()
          )
        .spanReporter(reporter)
        .build();
    
    return HttpTracing.create(tracing);
}
 
Example #3
Source File: TracingFactoryBeanTest.java    From brave with Apache License 2.0 5 votes vote down vote up
@Test public void currentTraceContext() {
  context = new XmlBeans(""
    + "<bean id=\"tracing\" class=\"brave.spring.beans.TracingFactoryBean\">\n"
    + "  <property name=\"currentTraceContext\">\n"
    + "    <bean class=\"brave.spring.beans.CurrentTraceContextFactoryBean\"/>\n"
    + "  </property>\n"
    + "</bean>"
  );

  assertThat(context.getBean("tracing", Tracing.class))
    .extracting("tracer.currentTraceContext")
    .isInstanceOf(ThreadLocalCurrentTraceContext.class);
}
 
Example #4
Source File: CurrentTraceContextFactoryBean.java    From brave with Apache License 2.0 5 votes vote down vote up
@Override public CurrentTraceContext getObject() {
  CurrentTraceContext.Builder builder = ThreadLocalCurrentTraceContext.newBuilder();
  if (scopeDecorators != null) {
    for (ScopeDecorator scopeDecorator : scopeDecorators) {
      builder.addScopeDecorator(scopeDecorator);
    }
  }
  if (customizers != null) {
    for (CurrentTraceContextCustomizer customizer : customizers) customizer.customize(builder);
  }
  return builder.build();
}
 
Example #5
Source File: EndToEndBenchmarks.java    From brave with Apache License 2.0 5 votes vote down vote up
public TracedCorrelated() {
  super(Tracing.newBuilder()
    .currentTraceContext(ThreadLocalCurrentTraceContext.newBuilder()
      // intentionally added twice to test overhead of multiple correlations
      .addScopeDecorator(ThreadContextScopeDecorator.get())
      .addScopeDecorator(ThreadContextScopeDecorator.get())
      .build())
    .addSpanHandler(new SpanHandler() {
      // intentionally not NOOP to ensure spans report
    })
    .build());
}
 
Example #6
Source File: CurrentTraceContextAssemblyTrackingClassLoaderTest.java    From brave with Apache License 2.0 5 votes vote down vote up
@Override public void run() {
  CurrentTraceContext currentTraceContext =
    ThreadLocalCurrentTraceContext.newBuilder().build();
  SavedHooks saved = new CurrentTraceContextAssemblyTracking(currentTraceContext)
    .enableAndChain();

  TraceContext assembly = TraceContext.newBuilder().traceId(1).spanId(1).build();

  try (Scope scope = currentTraceContext.newScope(assembly)) {
    Observable.just(1).map(i -> i).test().assertNoErrors();
  } finally {
    saved.restore();
  }
}
 
Example #7
Source File: TracingConfiguration.java    From brave-webmvc-example with MIT License 5 votes vote down vote up
/** Controls aspects of tracing such as the service name that shows up in the UI */
@Bean Tracing tracing(@Value("${zipkin.service:brave-webmvc-example}") String serviceName) {
  return Tracing.newBuilder()
      .localServiceName(serviceName)
      .propagationFactory(propagationFactory())
      .currentTraceContext(ThreadLocalCurrentTraceContext.newBuilder()
          .addScopeDecorator(correlationScopeDecorator())
          .build()
      )
      .spanReporter(spanReporter()).build();
}
 
Example #8
Source File: TracingConfiguration.java    From brave-webmvc-example with MIT License 5 votes vote down vote up
/** Controls aspects of tracing such as the service name that shows up in the UI */
@Bean Tracing tracing(@Value("${zipkin.service:brave-webmvc-example}") String serviceName) {
  return Tracing.newBuilder()
      .localServiceName(serviceName)
      .propagationFactory(propagationFactory())
      .currentTraceContext(ThreadLocalCurrentTraceContext.newBuilder()
          .addScopeDecorator(correlationScopeDecorator())
          .build()
      )
      .spanReporter(spanReporter()).build();
}
 
Example #9
Source File: CatalogTracingFactory.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static Tracing create(final String serviceName, final AsyncReporter<zipkin2.Span> reporter) {
    return Tracing
        .newBuilder()
        .localServiceName(serviceName)
        .currentTraceContext(
            ThreadLocalCurrentTraceContext
                .newBuilder()
                .build()
          )
        .spanReporter(reporter)
        .build();
}
 
Example #10
Source File: CatalogTracingFactory.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static Tracing create(final String serviceName, final AsyncReporter<zipkin2.Span> reporter) {
    return Tracing
        .newBuilder()
        .localServiceName(serviceName)
        .currentTraceContext(
            ThreadLocalCurrentTraceContext
                .newBuilder()
                .build()
          )
        .spanReporter(reporter)
        .build();
}
 
Example #11
Source File: TraceFilterTests.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
private Filter neverSampleFilter() {
	Tracing tracing = Tracing.newBuilder()
			.currentTraceContext(ThreadLocalCurrentTraceContext.newBuilder()
					.addScopeDecorator(StrictScopeDecorator.create()).build())
			.addSpanHandler(this.spans).sampler(Sampler.NEVER_SAMPLE)
			.supportsJoin(false).build();
	HttpTracing httpTracing = HttpTracing.newBuilder(tracing)
			.clientParser(new HttpClientParser()).serverParser(new HttpServerParser())
			.serverSampler(
					new SkipPatternHttpServerSampler(() -> Pattern.compile("")))
			.build();
	return TracingFilter.create(httpTracing);
}
 
Example #12
Source File: ZipkinTest.java    From hippo with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException, InterruptedException {
        URLConnectionSender sender = URLConnectionSender.create("http://103.10.0.67:9411/api/v2/spans");
        AsyncReporter reporter = AsyncReporter.builder(sender)
                .closeTimeout(100, TimeUnit.MILLISECONDS)
                .build(SpanBytesEncoder.JSON_V2);
        Tracing tracing = Tracing.newBuilder()
                .localServiceName("test1")
                .spanReporter(reporter)
                .propagationFactory(B3Propagation.FACTORY)
                .currentTraceContext(ThreadLocalCurrentTraceContext.create())
                .build();
        Tracer tracer = tracing.tracer();
        tracer.startScopedSpan("t1");
        Span span = tracer.newTrace().annotate("111").start();
        span.kind(Span.Kind.CLIENT);
       // span1.finish();
        // System.out.println(  span.context().traceId());
        //System.out.println(  span.context().spanId());
        //tracer.nextSpan().start();

       // Span span2=tracer.newChild(TraceContext.newBuilder().parentId(span.context().spanId()).traceId(span.context().traceId()).spanId(span.context().spanId()).build()).name("eeeee").annotate("222").start();
        // Span span2 = tracer.newChild(TraceContext.newBuilder().parentId(span.context().spanId()).traceId(span.context().traceId()).spanId(span.context().spanId()).build()).name("eeeee").start();
       // span2.kind(Span.Kind.SERVER);
//         System.out.println(  span.context().traceId());
//        System.out.println(  span.context().spanId());
        //System.out.println(span.annotate("").kind(Span.Kind.CLIENT));
        //Span action_1 = tracer.newChild(span.context()).name("action-1").start();
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            //span1.finish();
            span.finish();
            //    action_1.finish();
        }
        Thread.sleep(100000000L);
    }
 
Example #13
Source File: TracingConfiguration.java    From java-tutorial with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
/** Controls aspects of tracing such as the service name that shows up in the UI */
@Bean
Tracing tracing(@Value("${zipkin.service:brave-webmvc-example}") String serviceName) {
    return Tracing.newBuilder()
        .localServiceName(serviceName)
        .propagationFactory(ExtraFieldPropagation.newFactory(B3Propagation.FACTORY, "user-name"))
        .currentTraceContext(ThreadLocalCurrentTraceContext.newBuilder()
            .addScopeDecorator(ThreadContextScopeDecorator.create()) // puts trace IDs into logs
            .build()
        )
        .spanReporter(spanReporter()).build();
}
 
Example #14
Source File: TracingConfiguration.java    From java-tutorial with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
/** Controls aspects of tracing such as the service name that shows up in the UI */
@Bean Tracing tracing(@Value("${spring.application.name}") String serviceName) {
  return Tracing.newBuilder()
      .localServiceName(serviceName)
      .propagationFactory(ExtraFieldPropagation.newFactory(B3Propagation.FACTORY, "user-name"))
      .currentTraceContext(ThreadLocalCurrentTraceContext.newBuilder()
          .addScopeDecorator(MDCScopeDecorator.create()) // puts trace IDs into logs
          .build()
      )
      .spanReporter(spanReporter()).build();
}
 
Example #15
Source File: ZipkinSpanAspectTest.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Bean
Tracing tracing(Queue<Span> spans) {
  return Tracing.newBuilder()
      .currentTraceContext(
          ThreadLocalCurrentTraceContext.newBuilder().addScopeDecorator(StrictScopeDecorator.create()).build())
      .spanReporter(spans::add)
      .build();
}
 
Example #16
Source File: TraceAutoConfiguration.java    From spring-cloud-sleuth with Apache License 2.0 4 votes vote down vote up
@Bean
@ConditionalOnMissingBean
CurrentTraceContext.Builder sleuthCurrentTraceContextBuilder() {
	return ThreadLocalCurrentTraceContext.newBuilder();
}
 
Example #17
Source File: TracingConfiguration.java    From servicecomb-java-chassis with Apache License 2.0 4 votes vote down vote up
@Bean
CurrentTraceContext currentTraceContext() {
  return ThreadLocalCurrentTraceContext.newBuilder().addScopeDecorator(MDCScopeDecorator.create()).build();
}
 
Example #18
Source File: ZipkinRecordImpl.java    From hippo with Apache License 2.0 4 votes vote down vote up
@Override
public ZipkinResp start(ZipkinReq zipkinReq) {

    if (isInitError || zipkinReq == null || StringUtils.isBlank(zipkinUrl) || StringUtils.isBlank(zipkinReq.getServiceName())) {
        return null;
    }
    Tracing tracing = null;
    try {
        Span span;
        tracing = Tracing.newBuilder()
                .localServiceName(zipkinReq.getServiceName())
                .spanReporter(AsyncReporter.builder(URLConnectionSender.create(zipkinUrl))
                        .closeTimeout(100, TimeUnit.MILLISECONDS)
                        .build(SpanBytesEncoder.JSON_V2))
                .propagationFactory(B3Propagation.FACTORY)
                .currentTraceContext(ThreadLocalCurrentTraceContext.create())
                .build();
        if (zipkinReq.getParentSpanId() != null && zipkinReq.getParentTraceId() != null) {
            span = tracing.tracer().newChild(TraceContext.newBuilder()
                    .parentId(zipkinReq.getParentSpanId())
                    .traceId(zipkinReq.getParentTraceId())
                    .spanId(zipkinReq.getParentSpanId()).build());
        } else {
            span = tracing.tracer().newTrace();
        }

        if (StringUtils.isNotBlank(zipkinReq.getAnnotate())) {
            span.annotate(zipkinReq.getAnnotate());
        }
        if (StringUtils.isNotBlank(zipkinReq.getMethodName())) {
            span.name(zipkinReq.getMethodName());
        }

        if (zipkinReq.getSpanKind() != null) {
            if (zipkinReq.getSpanKind() == SpanKind.CLIENT) {
                span.kind(Span.Kind.CLIENT);
            } else {
                span.kind(Span.Kind.SERVER);
            }
        }
        if (zipkinReq.getTags() != null && !zipkinReq.getTags().isEmpty()) {
            for (String key : zipkinReq.getTags().keySet()) {
                span.tag(key, zipkinReq.getTags().get(key));
            }
        }
        span.start();
        ZipkinResp resp = new ZipkinResp();
        resp.setParentSpanId(Long.toHexString(span.context().spanId()));
        resp.setParentTraceId(Long.toHexString(span.context().traceId()));
        resp.setSpan(span);
        resp.setTracing(tracing);
        return resp;
    } catch (Exception e) {
        LOGGER.error("zipkin start error:" + zipkinUrl, e);
        close(tracing);
        isInitError = true;
    }
    return null;
}
 
Example #19
Source File: TraceHelper.java    From mdw with Apache License 2.0 4 votes vote down vote up
public static CurrentTraceContext getDefaultCurrentTraceContext() {
    return ThreadLocalCurrentTraceContext.newBuilder()
            .addScopeDecorator(MDCScopeDecorator.create())
            .build();
}
 
Example #20
Source File: MDCScopeDecoratorTest.java    From brave with Apache License 2.0 4 votes vote down vote up
@Override public CurrentTraceContext.Builder get() {
  return ThreadLocalCurrentTraceContext.newBuilder()
    .addScopeDecorator(MDCScopeDecorator.newBuilder().add(CORRELATION_FIELD).build());
}
 
Example #21
Source File: CurrentTraceContextAssemblyTrackingClassLoaderTest.java    From brave with Apache License 2.0 4 votes vote down vote up
@Override public void run() {
  new CurrentTraceContextAssemblyTracking(
    ThreadLocalCurrentTraceContext.newBuilder().build()
  ).enable();
  CurrentTraceContextAssemblyTracking.disable();
}
 
Example #22
Source File: AbstractZipkinFactory.java    From dropwizard-zipkin with Apache License 2.0 4 votes vote down vote up
/**
 * Build a new {@link HttpTracing} instance for interfacing with Zipkin
 *
 * @param environment Environment
 * @param reporter reporter
 * @return HttpTracing instance
 */
protected Optional<HttpTracing> buildTracing(
    final Environment environment, final SpanHandler reporter) {

  LOGGER.info(
      "Registering Zipkin service ({}) at <{}:{}>", serviceName, serviceHost, servicePort);

  final Tracing tracing =
      Tracing.newBuilder()
          .currentTraceContext(
              ThreadLocalCurrentTraceContext.newBuilder()
                  .addScopeDecorator(MDCScopeDecorator.get())
                  .build())
          .localIp(serviceHost)
          .localPort(servicePort)
          .addSpanHandler(reporter)
          .localServiceName(serviceName)
          .sampler(getSampler())
          .traceId128Bit(traceId128Bit)
          .build();

  final HttpTracing.Builder httpTracingBuilder = HttpTracing.newBuilder(tracing);
  if (clientParser != null) httpTracingBuilder.clientParser(clientParser);
  if (clientRequestParser != null) httpTracingBuilder.clientRequestParser(clientRequestParser);
  if (clientResponseParser != null) httpTracingBuilder.clientResponseParser(clientResponseParser);
  if (serverRequestParser != null) httpTracingBuilder.serverRequestParser(serverRequestParser);
  if (serverResponseParser != null) httpTracingBuilder.serverResponseParser(serverResponseParser);
  if (serverParser != null) httpTracingBuilder.serverParser(serverParser);
  if (clientSampler != null) httpTracingBuilder.clientSampler(clientSampler);
  if (serverSampler != null) httpTracingBuilder.serverSampler(serverSampler);

  final HttpTracing httpTracing = httpTracingBuilder.build();

  // Register the tracing feature for client and server requests
  environment.jersey().register(TracingApplicationEventListener.create(httpTracing));
  environment
      .lifecycle()
      .manage(
          new Managed() {
            @Override
            public void start() {
              // nothing to start
            }

            @Override
            public void stop() {
              tracing.close();
            }
          });

  return Optional.of(httpTracing);
}
 
Example #23
Source File: ThreadContextScopeDecoratorTest.java    From brave with Apache License 2.0 4 votes vote down vote up
@Override public CurrentTraceContext.Builder get() {
  return ThreadLocalCurrentTraceContext.newBuilder()
    .addScopeDecorator(ThreadContextScopeDecorator.newBuilder()
      .add(CORRELATION_FIELD).build());
}
 
Example #24
Source File: MDCScopeDecoratorTest.java    From brave with Apache License 2.0 4 votes vote down vote up
@Override public CurrentTraceContext.Builder get() {
  return ThreadLocalCurrentTraceContext.newBuilder()
    .addScopeDecorator(MDCScopeDecorator.newBuilder().add(CORRELATION_FIELD).build());
}