Java Code Examples for io.opencensus.common.Scope#close()

The following examples show how to use io.opencensus.common.Scope#close() . 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: JaxrsContainerFilter.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
@Override
public void filter(
    ContainerRequestContext requestContext, ContainerResponseContext responseContext)
    throws IOException {
  HttpRequestContext context = (HttpRequestContext) requestContext.getProperty(CONTEXT_PROPERTY);
  if (context == null) {
    // JAX-RS response filters are always invoked - we only want to record something if
    // request came through this filter
    return;
  }
  Scope scope = (Scope) requestContext.getProperty(SPAN_PROPERTY);
  if (scope != null) {
    scope.close();
  }
  if (responseContext.getLength() > 0) {
    handler.handleMessageSent(context, responseContext.getLength());
  }
  ExtendedContainerRequest extendedRequest = new ExtendedContainerRequest(requestContext, info);
  handler.handleEnd(context, extendedRequest, responseContext, null);
}
 
Example 2
Source File: MetricReader.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
/**
 * Reads the metrics from the {@link MetricProducerManager} and exports them to the {@code
 * metricExporter}.
 *
 * @param metricExporter the exporter called to export the metrics read.
 * @since 0.19
 */
public void readAndExport(MetricExporter metricExporter) {
  Span span =
      tracer
          .spanBuilder(spanName)
          .setRecordEvents(true)
          .setSampler(probabilitySampler)
          .startSpan();
  Scope scope = tracer.withSpan(span);
  try {
    ArrayList<Metric> metricsList = new ArrayList<>();
    for (MetricProducer metricProducer : metricProducerManager.getAllMetricProducer()) {
      metricsList.addAll(metricProducer.getMetrics());
    }
    metricExporter.export(metricsList);
  } catch (Throwable e) {
    logger.log(Level.WARNING, "Exception thrown by the metrics exporter.", e);
    span.setStatus(
        Status.UNKNOWN.withDescription("Exception when export metrics: " + exceptionMessage(e)));
  } finally {
    scope.close();
    span.end();
  }
}
 
Example 3
Source File: StackdriverV2ExporterHandler.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
@Override
public void export(Collection<SpanData> spanDataList) {
  // Start a new span with explicit 1/10000 sampling probability to avoid the case when user
  // sets the default sampler to always sample and we get the gRPC span of the stackdriver
  // export call always sampled and go to an infinite loop.
  io.opencensus.trace.Span span =
      tracer
          .spanBuilder(EXPORT_STACKDRIVER_TRACES)
          .setSampler(probabilitySampler)
          .setRecordEvents(true)
          .startSpan();
  Scope scope = tracer.withSpan(span);
  try {
    List<Span> spans = new ArrayList<>(spanDataList.size());
    for (SpanData spanData : spanDataList) {
      spans.add(generateSpan(spanData, RESOURCE_LABELS, fixedAttributes));
    }
    // Sync call because it is already called for a batch of data, and on a separate thread.
    // TODO(bdrutu): Consider to make this async in the future.
    traceServiceClient.batchWriteSpans(projectName, spans);
  } finally {
    scope.close();
    span.end(END_SPAN_OPTIONS);
  }
}
 
Example 4
Source File: Handler.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
static Object proceed(
    ProceedingJoinPoint call, Tracer tracer, String spanName, String... annotations)
    throws Throwable {
  Scope scope = tracer.spanBuilder(spanName).startScopedSpan();
  try {
    for (String annotation : annotations) {
      tracer.getCurrentSpan().addAnnotation(annotation);
    }

    return call.proceed();

  } catch (Throwable t) {
    Map<String, AttributeValue> attributes = new HashMap<String, AttributeValue>();
    String message = t.getMessage();
    attributes.put(
        "message", AttributeValue.stringAttributeValue(message == null ? "null" : message));
    attributes.put("type", AttributeValue.stringAttributeValue(t.getClass().toString()));

    Span span = tracer.getCurrentSpan();
    span.addAnnotation("error", attributes);
    span.setStatus(Status.UNKNOWN);
    throw t;
  } finally {
    scope.close();
  }
}
 
Example 5
Source File: TracingAsyncClientHttpRequestInterceptor.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
/**
 * It intercepts http requests and starts a span.
 *
 * @since 0.23.0
 */
public ListenableFuture<ClientHttpResponse> intercept(
    HttpRequest request,
    byte[] body,
    org.springframework.http.client.AsyncClientHttpRequestExecution execution)
    throws IOException {
  HttpRequestContext context = handler.handleStart(tracer.getCurrentSpan(), request, request);

  Scope ws = tracer.withSpan(handler.getSpanFromContext(context));
  try {
    ListenableFuture<ClientHttpResponse> result = execution.executeAsync(request, body);
    result.addCallback(
        new TracingAsyncClientHttpRequestInterceptor.TraceListenableFutureCallback(
            context, handler));
    return result;
  } catch (IOException e) {
    handler.handleEnd(context, null, null, e);
    throw e;
  } finally {
    if (ws != null) {
      ws.close();
    }
  }
}
 
Example 6
Source File: CurrentTagMapUtilsTest.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
@Test
public void testWithTagMapUsingWrap() {
  Runnable runnable;
  Scope scopedTags = CurrentTagMapUtils.withTagMap(tagContext);
  try {
    assertThat(CurrentTagMapUtils.getCurrentTagMap()).isSameInstanceAs(tagContext);
    runnable =
        Context.current()
            .wrap(
                new Runnable() {
                  @Override
                  public void run() {
                    assertThat(CurrentTagMapUtils.getCurrentTagMap())
                        .isSameInstanceAs(tagContext);
                  }
                });
  } finally {
    scopedTags.close();
  }
  assertThat(tagContextToList(CurrentTagMapUtils.getCurrentTagMap())).isEmpty();
  // When we run the runnable we will have the TagContext in the current Context.
  runnable.run();
}
 
Example 7
Source File: ScopedTagMapTest.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
@Test
public void addToCurrentTagsWithBuilder() {
  TagContext scopedTags = tagger.emptyBuilder().put(KEY_1, VALUE_1).build();
  Scope scope1 = tagger.withTagContext(scopedTags);
  try {
    Scope scope2 = tagger.currentBuilder().put(KEY_2, VALUE_2).buildScoped();
    try {
      assertThat(tagContextToList(tagger.getCurrentTagContext()))
          .containsExactly(Tag.create(KEY_1, VALUE_1), Tag.create(KEY_2, VALUE_2));
    } finally {
      scope2.close();
    }
    assertThat(tagger.getCurrentTagContext()).isSameInstanceAs(scopedTags);
  } finally {
    scope1.close();
  }
}
 
Example 8
Source File: ScopedTagMapTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void withTagContext() {
  assertThat(tagContextToList(tagger.getCurrentTagContext())).isEmpty();
  TagContext scopedTags = tagger.emptyBuilder().put(KEY_1, VALUE_1).build();
  Scope scope = tagger.withTagContext(scopedTags);
  try {
    assertThat(tagger.getCurrentTagContext()).isSameInstanceAs(scopedTags);
  } finally {
    scope.close();
  }
  assertThat(tagContextToList(tagger.getCurrentTagContext())).isEmpty();
}
 
Example 9
Source File: OpenCensusTraceContextDataInjectorTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void rawContextDataWithTracingData() {
  OpenCensusTraceContextDataInjector plugin = new OpenCensusTraceContextDataInjector();
  SpanContext spanContext =
      SpanContext.create(
          TraceId.fromLowerBase16("e17944156660f55b8cae5ce3f45d4a40"),
          SpanId.fromLowerBase16("fc3d2ba0d283b66a"),
          TraceOptions.builder().setIsSampled(true).build(),
          EMPTY_TRACESTATE);
  Scope scope = tracer.withSpan(new TestSpan(spanContext));
  try {
    String key = "myTestKey";
    ThreadContext.put(key, "myTestValue");
    try {
      assertThat(plugin.rawContextData().toMap())
          .containsExactly(
              "myTestKey",
              "myTestValue",
              "traceId",
              "e17944156660f55b8cae5ce3f45d4a40",
              "spanId",
              "fc3d2ba0d283b66a",
              "traceSampled",
              "true");
    } finally {
      ThreadContext.remove(key);
    }
  } finally {
    scope.close();
  }
}
 
Example 10
Source File: HttpClientHandlerTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void handleStartShouldCreateChildSpanInCurrentContext() {
  Scope scope = tracer.withSpan(parentSpan);
  try {
    HttpRequestContext context = handler.handleStart(null, carrier, request);
    verify(tracer).spanBuilderWithExplicitParent(any(String.class), same(parentSpan));
    assertThat(context.span).isEqualTo(childSpan);
  } finally {
    scope.close();
  }
}
 
Example 11
Source File: OpenCensusLog4jLogCorrelationTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
private static void logWithSpan(
    SpanContext spanContext, Function<Logger, Void> loggingFunction, Logger logger) {
  Scope scope = tracer.withSpan(new TestSpan(spanContext));
  try {
    loggingFunction.apply(logger);
  } finally {
    scope.close();
  }
}
 
Example 12
Source File: ScopedTagMapTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void setCurrentTagsWithBuilder() {
  assertThat(tagContextToList(tagger.getCurrentTagContext())).isEmpty();
  Scope scope = tagger.emptyBuilder().put(KEY_1, VALUE_1).buildScoped();
  try {
    assertThat(tagContextToList(tagger.getCurrentTagContext()))
        .containsExactly(Tag.create(KEY_1, VALUE_1));
  } finally {
    scope.close();
  }
  assertThat(tagContextToList(tagger.getCurrentTagContext())).isEmpty();
}
 
Example 13
Source File: ScopedTagMapTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void createBuilderFromCurrentTags() {
  TagContext scopedTags = tagger.emptyBuilder().put(KEY_1, VALUE_1).build();
  Scope scope = tagger.withTagContext(scopedTags);
  try {
    TagContext newTags = tagger.currentBuilder().put(KEY_2, VALUE_2).build();
    assertThat(tagContextToList(newTags))
        .containsExactly(Tag.create(KEY_1, VALUE_1), Tag.create(KEY_2, VALUE_2));
    assertThat(tagger.getCurrentTagContext()).isSameInstanceAs(scopedTags);
  } finally {
    scope.close();
  }
}
 
Example 14
Source File: CurrentSpanUtilsTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void withSpan_CloseDetaches() {
  assertThat(CurrentSpanUtils.getCurrentSpan()).isEqualTo(BlankSpan.INSTANCE);
  Scope ws = CurrentSpanUtils.withSpan(span, false);
  try {
    assertThat(CurrentSpanUtils.getCurrentSpan()).isSameInstanceAs(span);
  } finally {
    ws.close();
  }
  assertThat(CurrentSpanUtils.getCurrentSpan()).isEqualTo(BlankSpan.INSTANCE);
  verifyZeroInteractions(span);
}
 
Example 15
Source File: TaggerImplTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
private TagContext getResultOfWithTagContext(TagContext tagsToSet) {
  Scope scope = tagger.withTagContext(tagsToSet);
  try {
    return ContextUtils.getValue(Context.current());
  } finally {
    scope.close();
  }
}
 
Example 16
Source File: CurrentTagMapUtilsTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithTagMap() {
  assertThat(tagContextToList(CurrentTagMapUtils.getCurrentTagMap())).isEmpty();
  Scope scopedTags = CurrentTagMapUtils.withTagMap(tagContext);
  try {
    assertThat(CurrentTagMapUtils.getCurrentTagMap()).isSameInstanceAs(tagContext);
  } finally {
    scopedTags.close();
  }
  assertThat(tagContextToList(CurrentTagMapUtils.getCurrentTagMap())).isEmpty();
}
 
Example 17
Source File: OpenCensusTraceLoggingEnhancerTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
private static LogEntry getEnhancedLogEntry(LoggingEnhancer loggingEnhancer, Span span) {
  Scope scope = tracer.withSpan(span);
  try {
    LogEntry.Builder builder = LogEntry.newBuilder(null);
    loggingEnhancer.enhanceLogEntry(builder);
    return builder.build();
  } finally {
    scope.close();
  }
}
 
Example 18
Source File: TracerTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void startSpanWithInvalidParentFromContext() {
  Scope ws = tracer.withSpan(BlankSpan.INSTANCE);
  try {
    assertThat(tracer.getCurrentSpan()).isSameInstanceAs(BlankSpan.INSTANCE);
    when(tracer.spanBuilderWithExplicitParent(same(SPAN_NAME), same(BlankSpan.INSTANCE)))
        .thenReturn(spanBuilder);
    assertThat(tracer.spanBuilder(SPAN_NAME)).isSameInstanceAs(spanBuilder);
  } finally {
    ws.close();
  }
}
 
Example 19
Source File: TracerTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void startSpanWithParentFromContext() {
  Scope ws = tracer.withSpan(span);
  try {
    assertThat(tracer.getCurrentSpan()).isSameInstanceAs(span);
    when(tracer.spanBuilderWithExplicitParent(same(SPAN_NAME), same(span)))
        .thenReturn(spanBuilder);
    assertThat(tracer.spanBuilder(SPAN_NAME)).isSameInstanceAs(spanBuilder);
  } finally {
    ws.close();
  }
}
 
Example 20
Source File: CurrentSpanUtilsTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void withSpan_CloseDetachesAndEndsSpan() {
  assertThat(CurrentSpanUtils.getCurrentSpan()).isEqualTo(BlankSpan.INSTANCE);
  Scope ss = CurrentSpanUtils.withSpan(span, true);
  try {
    assertThat(CurrentSpanUtils.getCurrentSpan()).isSameInstanceAs(span);
  } finally {
    ss.close();
  }
  assertThat(CurrentSpanUtils.getCurrentSpan()).isEqualTo(BlankSpan.INSTANCE);
  verify(span).end(same(EndSpanOptions.DEFAULT));
}