org.springframework.cloud.sleuth.Span Java Examples

The following examples show how to use org.springframework.cloud.sleuth.Span. 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: OpenCensusSleuthTracer.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
@Override
@javax.annotation.Nullable
public Span createSpan(String name, /*@Nullable*/ Sampler sampler) {
  String shortenedName = SpanNameUtil.shorten(name);
  Span span;
  if (isTracing()) {
    span = createChild(getCurrentSpan(), shortenedName);
  } else {
    long id = createId();
    span =
        Span.builder()
            .name(shortenedName)
            .traceIdHigh(this.traceId128 ? createTraceIdHigh() : 0L)
            .traceId(id)
            .spanId(id)
            .build();
    if (sampler == null) {
      sampler = this.defaultSampler;
    }
    span = sampledSpan(span, sampler);
    this.spanLogger.logStartedSpan(null, span);
  }
  return continueSpan(span);
}
 
Example #2
Source File: SleuthModuleTest.java    From crnk-framework with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreate() {
	Task task = new Task();
	task.setId(13L);
	task.setName("myTask");
	taskRepo.create(task);

	// check client call and link span
	ArgumentCaptor<Span> clientSpanCaptor = ArgumentCaptor.forClass(Span.class);
	List<Span> clientSpans = clientSpanCaptor.getAllValues();
	Span callSpan = clientSpans.get(0);
	Assert.assertEquals("post", callSpan.getName());
	Assert.assertTrue(callSpan.toString().contains("\"cs\""));
	Assert.assertTrue(callSpan.toString().contains("\"cr\""));

	// check server local span
	Assert.assertEquals(1, reportedSpans.spans.size());
	Span repositorySpan = reportedSpans.spans.get(0);
	Assert.assertEquals("crnk:post:/tasks/13", repositorySpan.getName());
	Assert.assertTrue(repositorySpan.toString().contains("\"lc\""));

	assertBinaryAnnotation(repositorySpan, "lc", "crnk");
	assertBinaryAnnotation(repositorySpan, "crnk.query", "?");
}
 
Example #3
Source File: OpenCensusSleuthTracerTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testSpanStackAndContinue() {
  Span[] spans = createSpansAndAssertCurrent(3);
  Span original = tracer.getCurrentSpan();
  assertThat(original).isEqualTo(spans[spans.length - 1]);
  Span parent = tracer.detach(original);
  assertThat(parent).isEqualTo(spans[spans.length - 2]);
  assertThat(tracer.getCurrentSpan()).isNull();

  Span continued = tracer.continueSpan(original);
  assertCurrentSpanIs(continued);
  assertThat(continued.getSavedSpan()).isEqualTo(parent);
  assertThat(continued).isEqualTo(original);
  tracer.detach(continued);
}
 
Example #4
Source File: OpenCensusSleuthTracer.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Override
@javax.annotation.Nullable
public Span detach(/*@Nullable*/ Span span) {
  if (span == null) {
    return null;
  }
  Span current = OpenCensusSleuthSpanContextHolder.getCurrentSpan();
  if (current == null) {
    if (log.isTraceEnabled()) {
      log.trace(
          "Span in the context is null so something has already detached the span. "
              + "Won't do anything about it");
    }
    return null;
  }
  if (!span.equals(current)) {
    ExceptionUtils.warn(
        "Tried to detach trace span but "
            + "it is not the current span: "
            + span
            + ". You may have forgotten to close or detach "
            + current);
  } else {
    OpenCensusSleuthSpanContextHolder.removeCurrentSpan();
  }
  return span.getSavedSpan();
}
 
Example #5
Source File: OpenCensusSleuthTracer.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Override
@javax.annotation.Nullable
public Span close(/*@Nullable*/ Span span) {
  if (span == null) {
    return null;
  }
  final Span savedSpan = span.getSavedSpan();
  Span current = OpenCensusSleuthSpanContextHolder.getCurrentSpan();
  if (current == null || !span.equals(current)) {
    ExceptionUtils.warn(
        "Tried to close span but it is not the current span: "
            + span
            + ".  You may have forgotten to close or detach "
            + current);
  } else {
    span.stop();
    if (savedSpan != null && span.getParents().contains(savedSpan.getSpanId())) {
      this.spanReporter.report(span);
      this.spanLogger.logStoppedSpan(savedSpan, span);
    } else {
      if (!span.isRemote()) {
        this.spanReporter.report(span);
        this.spanLogger.logStoppedSpan(null, span);
      }
    }
    OpenCensusSleuthSpanContextHolder.close(
        new OpenCensusSleuthSpanContextHolder.SpanFunction() {
          @Override
          public void apply(Span closedSpan) {
            // Note: hasn't this already been done?
            OpenCensusSleuthTracer.this.spanLogger.logStoppedSpan(savedSpan, closedSpan);
          }
        });
  }
  return savedSpan;
}
 
Example #6
Source File: OpenCensusSleuthTracer.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
private static Span sampledSpan(Span span, Sampler sampler) {
  if (!sampler.isSampled(span)) {
    // Copy everything, except set exportable to false
    return Span.builder()
        .begin(span.getBegin())
        .traceIdHigh(span.getTraceIdHigh())
        .traceId(span.getTraceId())
        .spanId(span.getSpanId())
        .name(span.getName())
        .exportable(false)
        .build();
  }
  return span;
}
 
Example #7
Source File: OpenCensusSleuthTracer.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Override
@javax.annotation.Nullable
public Span continueSpan(/*@Nullable*/ Span span) {
  if (span != null) {
    this.spanLogger.logContinuedSpan(span);
  } else {
    return null;
  }
  Span newSpan = createContinuedSpan(span, OpenCensusSleuthSpanContextHolder.getCurrentSpan());
  OpenCensusSleuthSpanContextHolder.setCurrentSpan(newSpan);
  return newSpan;
}
 
Example #8
Source File: OpenCensusSleuthTracer.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
private static Span createContinuedSpan(Span span, /*@Nullable*/ Span saved) {
  if (saved == null && span.getSavedSpan() != null) {
    saved = span.getSavedSpan();
  }
  return new Span(span, saved);
}
 
Example #9
Source File: OpenCensusSleuthTracer.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Override
public void addTag(String key, String value) {
  Span s = getCurrentSpan();
  if (s != null && s.isExportable()) {
    s.tag(key, value);
  }
}
 
Example #10
Source File: OpenCensusSleuthTracerTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testRootSpanAndClose() {
  Span root = tracer.createSpan("root");
  assertCurrentSpanIs(root);
  assertThat(root.getSavedSpan()).isNull();
  Span parent = tracer.close(root);
  assertThat(parent).isNull();
}
 
Example #11
Source File: OpenCensusSleuthTracerTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testSpanStackAndClose() {
  Span[] spans = createSpansAndAssertCurrent(3);
  // pop the stack
  for (int i = spans.length - 1; i >= 0; i--) {
    assertCurrentSpanIs(spans[i]);
    Span parent = tracer.close(spans[i]);
    assertThat(parent).isEqualTo(spans[i].getSavedSpan());
  }
}
 
Example #12
Source File: OpenCensusSleuthTracerTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testSpanStackAndCloseOutOfOrder() {
  Span[] spans = createSpansAndAssertCurrent(3);
  // try to close a non-current span
  tracer.close(spans[spans.length - 2]);
  assertCurrentSpanIs(spans[spans.length - 1]);
  // pop the stack
  for (int i = spans.length - 1; i >= 0; i--) {
    tracer.close(spans[i]);
  }
}
 
Example #13
Source File: OpenCensusSleuthTracerTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testRootSpanAndDetach() {
  Span root = tracer.createSpan("root");
  assertCurrentSpanIs(root);
  assertThat(root.getSavedSpan()).isNull();
  Span parent = tracer.detach(root);
  assertThat(parent).isNull();
}
 
Example #14
Source File: OpenCensusSleuthTracerTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testSpanStackAndDetachOutOfOrder() {
  Span[] spans = createSpansAndAssertCurrent(3);
  // try to detach a non-current span
  tracer.detach(spans[spans.length - 2]);
  assertCurrentSpanIs(spans[spans.length - 1]);
  Span parent = tracer.detach(spans[spans.length - 1]);
  assertThat(parent).isEqualTo(spans[spans.length - 2]);
}
 
Example #15
Source File: OpenCensusSleuthTracerTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testRootSpanAndContinue() {
  Span root = tracer.createSpan("root");
  assertCurrentSpanIs(root);
  tracer.detach(root);
  Span span = tracer.continueSpan(root);
  assertThat(span).isEqualTo(root);
  tracer.detach(span);
}
 
Example #16
Source File: AcemFinancialUIApplication.java    From cat_lab with MIT License 5 votes vote down vote up
@RequestMapping("/readtimeout")
public String timeout() throws InterruptedException {
	Span span = this.tracer.createSpan("first_span");
	try {
		Thread.sleep(300);
		log.info("Hello from service1. Calling service2 - should end up with read timeout");
		String response = restTemplate.getForObject("http://" + serviceAddress + "/readtimeout", String.class);
		log.info("Got response from service2 [{}]", response);
		return response;
	} finally {
		this.tracer.close(span);
	}
}
 
Example #17
Source File: OpenCensusSleuthTracerTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testSpanStackAndCreateAndContinue() {
  createSpansAndAssertCurrent(3);
  Span original = tracer.getCurrentSpan();
  tracer.detach(original);
  Span root = tracer.createSpan("root");
  assertCurrentSpanIs(root);
  Span continued = tracer.continueSpan(original);
  assertCurrentSpanIs(continued);
  assertThat(continued.getSavedSpan()).isEqualTo(root);
  assertThat(continued).isEqualTo(original);
  assertThat(continued.getSavedSpan()).isNotEqualTo(original.getSavedSpan());
  tracer.detach(continued);
}
 
Example #18
Source File: OpenCensusSleuthTracerTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
private static void assertCurrentSpanIs(Span span) {
  assertThat(tracer.getCurrentSpan()).isEqualTo(span);
  assertThat(tracer.getCurrentSpan().getSavedSpan()).isEqualTo(span.getSavedSpan());

  assertThat(OpenCensusSleuthSpanContextHolder.getCurrentSpan()).isEqualTo(span);
  assertThat(OpenCensusSleuthSpanContextHolder.getCurrentSpan().getSavedSpan())
      .isEqualTo(span.getSavedSpan());
}
 
Example #19
Source File: OpenCensusSleuthTracerTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
private static Span[] createSpansAndAssertCurrent(int len) {
  Span[] spans = new Span[len];

  Span current = null;
  for (int i = 0; i < len; i++) {
    current = tracer.createSpan("span" + i, current);
    spans[i] = current;
    assertCurrentSpanIs(current);
  }
  return spans;
}
 
Example #20
Source File: OpenCensusSleuthSpanTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testFromSleuthSampled() {
  Span sleuthSpan =
      Span.builder()
          .name("name")
          .traceIdHigh(12L)
          .traceId(22L)
          .spanId(23L)
          .exportable(true)
          .build();
  assertSpanEquals(new OpenCensusSleuthSpan(sleuthSpan), sleuthSpan);
}
 
Example #21
Source File: OpenCensusSleuthSpanTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testFromSleuthNotSampled() {
  Span sleuthSpan =
      Span.builder()
          .name("name")
          .traceIdHigh(12L)
          .traceId(22L)
          .spanId(23L)
          .exportable(false)
          .build();
  assertSpanEquals(new OpenCensusSleuthSpan(sleuthSpan), sleuthSpan);
}
 
Example #22
Source File: OpenCensusSleuthSpanTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
private static final void assertSpanEquals(io.opencensus.trace.Span span, Span sleuthSpan) {
  assertThat(span.getContext().isValid()).isTrue();
  assertThat(Long.parseLong(span.getContext().getTraceId().toLowerBase16().substring(0, 16), 16))
      .isEqualTo(sleuthSpan.getTraceIdHigh());
  assertThat(Long.parseLong(span.getContext().getTraceId().toLowerBase16().substring(16, 32), 16))
      .isEqualTo(sleuthSpan.getTraceId());
  assertThat(Long.parseLong(span.getContext().getSpanId().toLowerBase16(), 16))
      .isEqualTo(sleuthSpan.getSpanId());
  assertThat(span.getContext().getTraceOptions().isSampled())
      .isEqualTo(sleuthSpan.isExportable());
}
 
Example #23
Source File: JdbcTraceAspect.java    From docker-kubernetes-by-example-java with Apache License 2.0 5 votes vote down vote up
@Around("execution (* org.springframework.jdbc.core.JdbcTemplate.*(..))")
public Object traceJdbcCall(final ProceedingJoinPoint pjp) throws Throwable {
  String spanName = SpanNameUtil.toLowerHyphen(pjp.getSignature().getName());
  Span span = this.tracer.createSpan("jdbc:/" + spanName);
  try {
    return pjp.proceed();
  }
  finally {
    this.tracer.close(span);
  }
}
 
Example #24
Source File: SleuthDbmInterceptor.java    From onetwo with Apache License 2.0 5 votes vote down vote up
@Override
	public Object intercept(DbmInterceptorChain chain) {
		final Span span = tracer.createSpan(SPAN_NAME);
		try {
			span.tag(Span.SPAN_LOCAL_COMPONENT_TAG_NAME, SPAN_NAME);
			span.logEvent(Span.CLIENT_SEND);
			return chain.invoke();
		} finally{
//			span.tag(Span.SPAN_PEER_SERVICE_TAG_NAME, SPAN_NAME);
			span.logEvent(Span.CLIENT_RECV);
			tracer.close(span);
		}
	}
 
Example #25
Source File: SleuthRocketmqInterceptor.java    From onetwo with Apache License 2.0 5 votes vote down vote up
@Override
public Object intercept(SendMessageInterceptorChain chain) {
	if (tracer!=null) {
		return chain.invoke();
	}
	final Span span = tracer.createSpan(SPAN_NAME);
	try {
		span.tag(Span.SPAN_LOCAL_COMPONENT_TAG_NAME, SPAN_NAME);
		span.logEvent(Span.CLIENT_SEND);
		return chain.invoke();
	} finally{
		span.logEvent(Span.CLIENT_RECV);
		tracer.close(span);
	}
}
 
Example #26
Source File: BeanConversionService.java    From data-prep with Apache License 2.0 5 votes vote down vote up
@Override
@NewSpan("conversion")
public <U> U convert(Object source, @SpanTag("target") Class<U> targetClass) {
    if (source == null) {
        return null;
    }
    if (tracer != null) {
        tracer.addTag(Span.SPAN_LOCAL_COMPONENT_TAG_NAME, BeanConversionService.class.getName());
        tracer.addTag("source", "class " + source.getClass().getName());
    }
    if (source.getClass().equals(targetClass)) {
        return (U) source;
    }
    try {
        U converted = targetClass.newInstance();
        copyBean(source, converted);

        List<Registration<Object>> registrationsFound = getRegistrationsForSourceClass(source.getClass());

        List<BiFunction<Object, U, U>> customs = new ArrayList<>();
        for (Registration<Object> registrationFound : registrationsFound) {
            customs.addAll(getRegistrationFunctions(targetClass, registrationFound));
        }

        U result = converted;
        for (BiFunction<Object, U, U> current : customs) {
            result = current.apply(source, converted);
        }

        return result;
    } catch (InstantiationException | IllegalAccessException e) {
        throw new RuntimeException(e);
    }
}
 
Example #27
Source File: GenericCommand.java    From data-prep with Apache License 2.0 5 votes vote down vote up
private Span addTrackingHeaders(HttpRequestBase request) {
    final Package commandPackage = this.getClass().getPackage();
    final StringTokenizer tokenizer = new StringTokenizer(commandPackage.getName(), ".");
    final StringBuilder spanName = new StringBuilder();
    while (tokenizer.hasMoreTokens()) {
        spanName.append(String.valueOf(tokenizer.nextToken().charAt(0) + "."));
    }
    spanName.append(this.getClass().getSimpleName());

    final Span requestSpan = tracer.createSpan(spanName.toString(), tracer.getCurrentSpan());
    requestSpan.tag(Span.SPAN_LOCAL_COMPONENT_TAG_NAME, this.getClass().getName());
    final SpanInjector<HttpRequestBase> injector = new HttpRequestBaseSpanInjector(this.getClass());
    injector.inject(requestSpan, request);
    return requestSpan;
}
 
Example #28
Source File: GenericCommand.java    From data-prep with Apache License 2.0 5 votes vote down vote up
public void inject(Span span, HttpRequestBase httpRequestBase) {
    this.setIdHeader(httpRequestBase, Span.TRACE_ID_NAME, span.getTraceId());
    this.setIdHeader(httpRequestBase, Span.SPAN_ID_NAME, span.getSpanId());
    this.setHeader(httpRequestBase, Span.SAMPLED_NAME, span.isExportable() ? "1" : "0");
    this.setHeader(httpRequestBase, SPAN_NAME_NAME, span.getName());
    this.setIdHeader(httpRequestBase, Span.PARENT_ID_NAME, this.getParentId(span));
    this.setHeader(httpRequestBase, Span.PROCESS_ID_NAME, span.getProcessId());
    this.setHeader(httpRequestBase, Span.SPAN_LOCAL_COMPONENT_TAG_NAME, commandClass.getName());
}
 
Example #29
Source File: OpenCensusSleuthTracer.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Override
@javax.annotation.Nullable
public Span createSpan(String name, /*@Nullable*/ Span parent) {
  if (parent == null) {
    return createSpan(name);
  }
  return continueSpan(createChild(parent, name));
}
 
Example #30
Source File: AcmeFinancialBackOfficeApplication.java    From cat_lab with MIT License 5 votes vote down vote up
@RequestMapping("/readtimeout")
public String connectionTimeout() throws InterruptedException {
	Span span = this.tracer.createSpan("second_span");
	Thread.sleep(500);
	try {
		log.info("Calling a missing service");
		restTemplate.getForObject("http://localhost:" + MOCK_PORT + "/readtimeout", String.class);
		return "Should blow up";
	} finally {
		this.tracer.close(span);
	}
}