io.opencensus.common.Scope Java Examples
The following examples show how to use
io.opencensus.common.Scope.
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: GooglePubsub.java From metastore with Apache License 2.0 | 7 votes |
@Override public void descriptorsChanged(Report report) { try (Scope scope = TRACER .spanBuilder("GooglePubsub.descriptorsChanged") .setRecordEvents(true) .startScopedSpan()) { PubsubMessage message = PubsubMessage.newBuilder().setData(report.toByteString()).build(); ApiFuture<String> future = publisherDescriptorChange.publish(message); ApiFutures.addCallback( future, new ApiFutureCallback<String>() { @Override public void onFailure(Throwable t) { LOG.error("Error publishing changes to Pubsub", t); } @Override public void onSuccess(String messageId) { LOG.debug("Published changes to Pubsub"); } }, MoreExecutors.directExecutor()); } }
Example #2
Source File: OcAgentExportersQuickStart.java From opencensus-java with Apache License 2.0 | 6 votes |
/** Main launcher of the example. */ public static void main(String[] args) throws InterruptedException { configureAlwaysSample(); // Always sample for demo purpose. DO NOT use in production. registerAllViews(); LongGauge gauge = registerGauge(); String endPoint = getStringOrDefaultFromArgs(args, 0, DEFAULT_ENDPOINT); registerAgentExporters(endPoint); try (Scope scope = tracer.spanBuilder("root").startScopedSpan()) { int iteration = 1; while (true) { doWork(iteration, random.nextInt(10), gauge); iteration++; Thread.sleep(5000); } } catch (InterruptedException e) { logger.info("Thread interrupted, exiting in 5 seconds."); Thread.sleep(5000); // Wait 5s so that last batch will be exported. } }
Example #3
Source File: GoogleDtpInternalMetricRecorder.java From data-transfer-project with Apache License 2.0 | 6 votes |
@Override public void exportPageAttemptFinished( String dataType, String service, boolean success, Duration duration) { TagContext tctx = tagger.emptyBuilder() .put(KEY_DATA_TYPE, TagValue.create(dataType), TAG_METADATA) .put(KEY_EXPORT_SERVICE, TagValue.create(service), TAG_METADATA) .put(KEY_SUCCESS, TagValue.create(Boolean.toString(success)), TAG_METADATA) .build(); try (Scope ss = tagger.withTagContext(tctx)) { STATS_RECORDER.newMeasureMap() .put(EXPORT_PAGE_ATTEMPT, 1) .put(EXPORT_PAGE_ATTEMPT_DURATION, duration.toMillis()) .record(); } }
Example #4
Source File: Handler.java From opencensus-java with Apache License 2.0 | 6 votes |
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: GoogleDtpInternalMetricRecorder.java From data-transfer-project with Apache License 2.0 | 6 votes |
@Override public void exportPageFinished( String dataType, String service, boolean success, Duration duration) { TagContext tctx = tagger.emptyBuilder() .put(KEY_DATA_TYPE, TagValue.create(dataType), TAG_METADATA) .put(KEY_EXPORT_SERVICE, TagValue.create(service), TAG_METADATA) .put(KEY_SUCCESS, TagValue.create(Boolean.toString(success)), TAG_METADATA) .build(); try (Scope ss = tagger.withTagContext(tctx)) { STATS_RECORDER.newMeasureMap() .put(EXPORT_PAGE, 1) .put(EXPORT_PAGE_DURATION, duration.toMillis()) .record(); } }
Example #6
Source File: HelloWorldClient.java From opencensus-java with Apache License 2.0 | 6 votes |
/** 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()); }
Example #7
Source File: TagContextExample.java From opencensus-java with Apache License 2.0 | 6 votes |
/** * Main method. * * @param args the main arguments. */ public static void main(String[] args) { System.out.println("Hello Stats World"); System.out.println("Default Tags: " + tagger.empty()); System.out.println("Current Tags: " + tagger.getCurrentTagContext()); TagContext tags1 = tagger.emptyBuilder().put(K1, V1).put(K2, V2).build(); try (Scope scopedTagCtx1 = tagger.withTagContext(tags1)) { System.out.println(" Current Tags: " + tagger.getCurrentTagContext()); System.out.println( " Current == Default + tags1: " + tagger.getCurrentTagContext().equals(tags1)); TagContext tags2 = tagger.toBuilder(tags1).put(K3, V3).put(K4, V4).build(); try (Scope scopedTagCtx2 = tagger.withTagContext(tags2)) { System.out.println(" Current Tags: " + tagger.getCurrentTagContext()); System.out.println( " Current == Default + tags1 + tags2: " + tagger.getCurrentTagContext().equals(tags2)); statsRecorder.newMeasureMap().put(M1, 0.2).put(M2, 0.4).record(); } } System.out.println( "Current == Default: " + tagger.getCurrentTagContext().equals(tagger.empty())); }
Example #8
Source File: OcAgentExportersQuickStart.java From opencensus-java with Apache License 2.0 | 6 votes |
private static void doWork(int iteration, int jobs, LongGauge gauge) { String childSpanName = "iteration-" + iteration; LabelValue value = LabelValue.create(childSpanName); LongPoint point = gauge.getOrCreateTimeSeries(Collections.singletonList(value)); try (Scope scope = tracer.spanBuilder(childSpanName).startScopedSpan()) { for (int i = 0; i < jobs; i++) { String grandChildSpanName = childSpanName + "-job-" + i; try (Scope childScope = tracer.spanBuilder(grandChildSpanName).startScopedSpan()) { point.set(jobs - i); String line = generateRandom(random.nextInt(128)); processLine(line); recordStat(M_LINES_IN, 1L); recordStat(M_LINE_LENGTHS, (long) line.length()); } catch (Exception e) { tracer.getCurrentSpan().setStatus(Status.INTERNAL.withDescription(e.toString())); } } } }
Example #9
Source File: CurrentTagMapUtilsTest.java From opencensus-java with Apache License 2.0 | 6 votes |
@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 #10
Source File: JaxrsContainerFilter.java From opencensus-java with Apache License 2.0 | 6 votes |
@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 #11
Source File: MetricReader.java From opencensus-java with Apache License 2.0 | 6 votes |
/** * 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 #12
Source File: GoogleDtpInternalMetricRecorder.java From data-transfer-project with Apache License 2.0 | 6 votes |
@Override public void importPageAttemptFinished( String dataType, String service, boolean success, Duration duration) { TagContext tctx = tagger.emptyBuilder() .put(KEY_DATA_TYPE, TagValue.create(dataType), TAG_METADATA) .put(KEY_IMPORT_SERVICE, TagValue.create(service), TAG_METADATA) .put(KEY_SUCCESS, TagValue.create(Boolean.toString(success)), TAG_METADATA) .build(); try (Scope ss = tagger.withTagContext(tctx)) { STATS_RECORDER.newMeasureMap() .put(IMPORT_PAGE_ATTEMPT, 1) .put(IMPORT_PAGE_ATTEMPT_DURATION, duration.toMillis()) .record(); } }
Example #13
Source File: OcAgentTraceExporterIntegrationTest.java From opencensus-java with Apache License 2.0 | 6 votes |
private void doWork(String spanName, int i) { try (Scope scope = tracer.spanBuilder(spanName).startScopedSpan()) { // Simulate some work. Span span = tracer.getCurrentSpan(); try { Thread.sleep(10L); } catch (InterruptedException e) { span.setStatus(Status.INTERNAL.withDescription(e.toString())); } Map<String, AttributeValue> attributes = new HashMap<String, AttributeValue>(); attributes.put("inner work iteration number", AttributeValue.longAttributeValue(i)); span.addAnnotation("Invoking doWork", attributes); } }
Example #14
Source File: GoogleDtpInternalMetricRecorder.java From data-transfer-project with Apache License 2.0 | 6 votes |
@Override public void finishedJob( String dataType, String exportService, String importService, boolean success, Duration duration) { TagContext tctx = tagger.emptyBuilder() .put(KEY_DATA_TYPE, TagValue.create(dataType), TAG_METADATA) .put(KEY_EXPORT_SERVICE, TagValue.create(exportService), TAG_METADATA) .put(KEY_IMPORT_SERVICE, TagValue.create(importService), TAG_METADATA) .put(KEY_SUCCESS, TagValue.create(Boolean.toString(success)), TAG_METADATA) .build(); try (Scope ss = tagger.withTagContext(tctx)) { STATS_RECORDER.newMeasureMap() .put(JOB_FINISHED, 1) .put(JOB_FINISHED_DURATION, duration.toMillis()) .record(); } }
Example #15
Source File: MultiSpansScopedTracing.java From opencensus-java with Apache License 2.0 | 6 votes |
/** * 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); }
Example #16
Source File: TracingAsyncClientHttpRequestInterceptor.java From opencensus-java with Apache License 2.0 | 6 votes |
/** * 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 #17
Source File: StackdriverV2ExporterHandler.java From opencensus-java with Apache License 2.0 | 6 votes |
@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 #18
Source File: ScopedTagMapTest.java From opencensus-java with Apache License 2.0 | 6 votes |
@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 #19
Source File: SpanBuilderTest.java From opencensus-java with Apache License 2.0 | 5 votes |
@Test public void startScopedSpan() { assertThat(tracer.getCurrentSpan()).isSameInstanceAs(BlankSpan.INSTANCE); Scope scope = spanBuilder.startScopedSpan(); try { assertThat(tracer.getCurrentSpan()).isSameInstanceAs(span); } finally { scope.close(); } verify(span).end(EndSpanOptions.DEFAULT); assertThat(tracer.getCurrentSpan()).isSameInstanceAs(BlankSpan.INSTANCE); }
Example #20
Source File: BasicOperationsBenchmark.java From opencensus-java with Apache License 2.0 | 5 votes |
/** Scope/Unscope a trace span. */ @Benchmark @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) public Scope scopeSpan(Data data) { try (Scope scope = data.tracer.withSpan(data.spanToScope)) { return scope; } }
Example #21
Source File: BeamFnMapTaskExecutor.java From beam with Apache License 2.0 | 5 votes |
@Override public void execute() throws Exception { Tracer tracer = Tracing.getTracer(); SpanBuilder builder = tracer.spanBuilder("MapTaskExecutor.Span").setRecordEvents(true); // Start the progress tracker before execution (which blocks until execution is finished). try (Scope unused = builder.startScopedSpan(); AutoCloseable unused2 = progressTrackerCloseable(progressTracker)) { tracer.getCurrentSpan().addAnnotation("About to execute"); super.execute(); tracer.getCurrentSpan().addAnnotation("Done with execute"); } }
Example #22
Source File: HelloWorldServer.java From opencensus-java with Apache License 2.0 | 5 votes |
private static void performWork(Span parent) { SpanBuilder spanBuilder = tracer .spanBuilderWithExplicitParent("internal_work", parent) .setRecordEvents(true) .setSampler(Samplers.alwaysSample()); try (Scope scope = spanBuilder.startScopedSpan()) { Span span = tracer.getCurrentSpan(); span.putAttribute("my_attribute", AttributeValue.stringAttributeValue("blue")); span.addAnnotation("Performing work."); sleepFor(20); // Working hard here. span.addAnnotation("Done work."); } }
Example #23
Source File: ScopedTagMapTest.java From opencensus-java with Apache License 2.0 | 5 votes |
@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 #24
Source File: QuickStart.java From opencensus-java with Apache License 2.0 | 5 votes |
/** 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(); // Process video. // 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)); }
Example #25
Source File: OpenCensusTraceContextDataInjectorTest.java From opencensus-java with Apache License 2.0 | 5 votes |
@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 #26
Source File: Scheduler.java From styx with Apache License 2.0 | 5 votes |
void tick() { try (Scope ignored = tracer.spanBuilder("Styx.Scheduler.tick") .setRecordEvents(true) .setSampler(Samplers.alwaysSample()) .startScopedSpan()) { tick0(); } }
Example #27
Source File: Cleaner.java From styx with Apache License 2.0 | 5 votes |
void tick() { try (Scope ignored = tracer.spanBuilder("Styx.Cleaner.tick") .setRecordEvents(true) .setSampler(Samplers.alwaysSample()) .startScopedSpan()) { tick0(); } }
Example #28
Source File: BackfillTriggerManager.java From styx with Apache License 2.0 | 5 votes |
void tick() { try (Scope ignored = tracer.spanBuilder("Styx.BackfillTriggerManager.tick") .setRecordEvents(true) .setSampler(Samplers.alwaysSample()) .startScopedSpan()) { tick0(); } }
Example #29
Source File: GoogleDataCatalog.java From metastore with Apache License 2.0 | 5 votes |
@Override public void createResourceBinding(String resourceUrn, Descriptors.Descriptor descriptor) { try (Scope scope = TRACER .spanBuilder("GoogleDataCatalog.createResourceBinding") .setRecordEvents(true) .startScopedSpan()) { dataCatalogClient.createTag( CreateTagRequest.newBuilder() .setParent("") .setTag(Tag.newBuilder().setName("xxx").build()) .build()); } }
Example #30
Source File: KubernetesDockerRunner.java From styx with Apache License 2.0 | 5 votes |
private void cleanupPods() { try { try (Scope ignored = tracer.spanBuilder("Styx.KubernetesDockerRunner.cleanupPods") .setRecordEvents(true) .setSampler(Samplers.alwaysSample()) .startScopedSpan()) { tryCleanupPods(); } } catch (Throwable t) { LOG.warn("Error while cleaning pods", t); } }