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));
}
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);
}
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();
}
}
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());
}
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();
}
Aggregations