Search in sources :

Example 36 with Scope

use of io.opencensus.common.Scope in project instrumentation-java by census-instrumentation.

the class QuickStart method main.

/**
 * Main launcher for the QuickStart example.
 */
public static void main(String[] args) throws InterruptedException {
    TagContextBuilder tagContextBuilder = tagger.currentBuilder().put(FRONTEND_KEY, TagValue.create("mobile-ios9.3.5"));
    SpanBuilder spanBuilder = tracer.spanBuilder("my.org/ProcessVideo").setRecordEvents(true).setSampler(Samplers.alwaysSample());
    viewManager.registerView(VIDEO_SIZE_VIEW);
    LoggingTraceExporter.register();
    // Record the processed video size.
    try (Scope scopedTags = tagContextBuilder.buildScoped();
        Scope scopedSpan = spanBuilder.startScopedSpan()) {
        tracer.getCurrentSpan().addAnnotation("Start processing video.");
        // Sleep for [0,10] milliseconds to fake work.
        Thread.sleep(new Random().nextInt(10) + 1);
        statsRecorder.newMeasureMap().put(VIDEO_SIZE, 25 * MiB).record();
        tracer.getCurrentSpan().addAnnotation("Finished processing video.");
    } catch (Exception e) {
        tracer.getCurrentSpan().addAnnotation("Exception thrown when processing video.");
        tracer.getCurrentSpan().setStatus(Status.UNKNOWN);
        logger.severe(e.getMessage());
    }
    logger.info("Wait longer than the reporting duration...");
    // Wait for a duration longer than reporting duration (5s) to ensure spans are exported.
    // TODO(songya): remove the gap once we add a shutdown hook for exporting unflushed spans.
    Thread.sleep(5100);
    ViewData viewData = viewManager.getView(VIDEO_SIZE_VIEW_NAME);
    logger.info(String.format("Recorded stats for %s:\n %s", VIDEO_SIZE_VIEW_NAME.asString(), viewData));
}
Also used : SpanBuilder(io.opencensus.trace.SpanBuilder) Scope(io.opencensus.common.Scope) Random(java.util.Random) ViewData(io.opencensus.stats.ViewData) TagContextBuilder(io.opencensus.tags.TagContextBuilder)

Example 37 with Scope

use of io.opencensus.common.Scope in project instrumentation-java by census-instrumentation.

the class MultiSpansScopedTracing method main.

/**
 * Main method.
 *
 * @param args the main arguments.
 */
public static void main(String[] args) {
    // WARNING: Be careful before you set sampler value to always sample, especially in
    // production environment. Trace data is often very large in size and is expensive to
    // collect. This is why rather than collecting traces for every request(i.e. alwaysSample),
    // downsampling is prefered.
    // 
    // By default, OpenCensus provides a probabilistic sampler that will trace once in every
    // 10,000 requests, that's why if default probabilistic sampler is used
    // you might not see trace data printed or exported and this is expected behavior.
    TraceConfig traceConfig = Tracing.getTraceConfig();
    traceConfig.updateActiveTraceParams(traceConfig.getActiveTraceParams().toBuilder().setSampler(Samplers.alwaysSample()).build());
    LoggingTraceExporter.register();
    try (Scope ss = tracer.spanBuilderWithExplicitParent("MyRootSpan", null).startScopedSpan()) {
        doWork();
    }
    // Wait for a duration longer than reporting duration (5s) to ensure spans are exported.
    // Spans are exported every 5 seconds
    sleep(5100);
}
Also used : Scope(io.opencensus.common.Scope) TraceConfig(io.opencensus.trace.config.TraceConfig)

Example 38 with Scope

use of io.opencensus.common.Scope in project instrumentation-java by census-instrumentation.

the class OpenCensusTraceContextDataInjectorTest method rawContextDataWithTracingData.

@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();
    }
}
Also used : SpanContext(io.opencensus.trace.SpanContext) Scope(io.opencensus.common.Scope) Test(org.junit.Test)

Example 39 with Scope

use of io.opencensus.common.Scope in project instrumentation-java by census-instrumentation.

the class HelloWorldClient method greet.

/**
 * Say hello to server.
 */
public void greet(String name) {
    logger.info("Will try to greet " + name + " ...");
    HelloRequest request = HelloRequest.newBuilder().setName(name).build();
    HelloReply response;
    SpanBuilder spanBuilder = tracer.spanBuilder("client").setRecordEvents(true).setSampler(Samplers.alwaysSample());
    try (Scope scope = spanBuilder.startScopedSpan()) {
        tracer.getCurrentSpan().addAnnotation("Saying Hello to Server.");
        response = blockingStub.sayHello(request);
        tracer.getCurrentSpan().addAnnotation("Received response from Server.");
    } catch (StatusRuntimeException e) {
        tracer.getCurrentSpan().setStatus(CanonicalCode.valueOf(e.getStatus().getCode().name()).toStatus().withDescription(e.getMessage()));
        logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus());
        return;
    }
    logger.info("Greeting: " + response.getMessage());
}
Also used : SpanBuilder(io.opencensus.trace.SpanBuilder) Scope(io.opencensus.common.Scope) StatusRuntimeException(io.grpc.StatusRuntimeException)

Example 40 with Scope

use of io.opencensus.common.Scope in project instrumentation-java by census-instrumentation.

the class TraceWebAsyncClientAutoConfigurationTest method should_close_span_upon_success_callback.

@Test(timeout = 10000)
@Order(1)
public void should_close_span_upon_success_callback() throws ExecutionException, InterruptedException {
    tracer = Tracing.getTracer();
    Span initialSpan = tracer.spanBuilder("initial").startSpan();
    try (Scope ws = tracer.withSpan(initialSpan)) {
        ListenableFuture<ResponseEntity<String>> future = asyncRestTemplate.getForEntity("http://localhost:" + port() + "/async", String.class);
        String result = future.get().getBody();
        assertThat(result).isEqualTo("async");
    } finally {
        initialSpan.end();
    }
    // 3 spans are initial, client, server.
    List<SpanData> spans = handler.waitForExport(3);
    SpanData clientSpan = null;
    for (SpanData span : spans) {
        if (span.getKind() == CLIENT) {
            clientSpan = span;
            assertThat(clientSpan.getName()).isEqualTo("/async");
            assertThat(clientSpan.getStatus().isOk()).isTrue();
            assertThat(clientSpan.getAttributes().getAttributeMap().get(HttpTraceAttributeConstants.HTTP_METHOD)).isEqualTo(AttributeValue.stringAttributeValue("GET"));
            assertThat(clientSpan.getAttributes().getAttributeMap().get(HttpTraceAttributeConstants.HTTP_HOST)).isEqualTo(AttributeValue.stringAttributeValue("localhost"));
            assertThat(clientSpan.getAttributes().getAttributeMap().get(HttpTraceAttributeConstants.HTTP_PATH)).isEqualTo(AttributeValue.stringAttributeValue("/async"));
            assertThat(clientSpan.getKind()).isEqualTo(CLIENT);
            break;
        }
    }
    assertThat(clientSpan).isNotNull();
}
Also used : ResponseEntity(org.springframework.http.ResponseEntity) Scope(io.opencensus.common.Scope) SpanData(io.opencensus.trace.export.SpanData) Span(io.opencensus.trace.Span) Order(org.springframework.core.annotation.Order) Test(org.junit.Test) SpringBootTest(org.springframework.boot.test.context.SpringBootTest)

Aggregations

Scope (io.opencensus.common.Scope)48 Test (org.junit.Test)18 Span (io.opencensus.trace.Span)8 Timestamp (com.google.cloud.Timestamp)5 TagContext (io.opencensus.tags.TagContext)5 SpanBuilder (io.opencensus.trace.SpanBuilder)5 VisibleForTesting (org.apache.beam.vendor.guava.v26_0_jre.com.google.common.annotations.VisibleForTesting)5 ArrayList (java.util.ArrayList)4 Instant (org.joda.time.Instant)4 HttpRequestContext (io.opencensus.contrib.http.HttpRequestContext)3 SimpleTimeLimiter (com.google.common.util.concurrent.SimpleTimeLimiter)2 TimeLimiter (com.google.common.util.concurrent.TimeLimiter)2 ByteString (com.google.protobuf.ByteString)2 LongPoint (io.opencensus.metrics.LongGauge.LongPoint)2 MeasureMap (io.opencensus.stats.MeasureMap)2 TagContextBuilder (io.opencensus.tags.TagContextBuilder)2 AttributeValue (io.opencensus.trace.AttributeValue)2 Tracer (io.opencensus.trace.Tracer)2 TraceConfig (io.opencensus.trace.config.TraceConfig)2 HashMap (java.util.HashMap)2