Java Code Examples for io.opencensus.trace.Span#putAttribute()

The following examples show how to use io.opencensus.trace.Span#putAttribute() . 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: HelloWorldServer.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
@Override
public void sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver) {
  Span span = tracer.getCurrentSpan();
  span.putAttribute("my_attribute", AttributeValue.stringAttributeValue("red"));
  span.addAnnotation(
      "Constructing greeting.",
      ImmutableMap.of(
          "name", AttributeValue.stringAttributeValue(req.getName()),
          "name length", AttributeValue.longAttributeValue(req.getName().length())));
  sleepFor(10);
  performWork(span);
  span.addAnnotation("Sleeping.");
  sleepFor(30);
  HelloReply reply = HelloReply.newBuilder().setMessage("Hello " + req.getName()).build();
  responseObserver.onNext(reply);
  responseObserver.onCompleted();
  logger.info("SayHello RPC handled.");
}
 
Example 2
Source File: ZPageHttpHandler.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
@Override
public final void handle(HttpExchange httpExchange) throws IOException {
  Span span =
      tracer
          .spanBuilderWithExplicitParent(httpServerSpanName, null)
          .setRecordEvents(true)
          .startSpan();
  try (Scope ss = tracer.withSpan(span)) {
    span.putAttribute(
        "/http/method ", AttributeValue.stringAttributeValue(httpExchange.getRequestMethod()));
    httpExchange.sendResponseHeaders(200, 0);
    zpageHandler.emitHtml(
        uriQueryToMap(httpExchange.getRequestURI()), httpExchange.getResponseBody());
  } finally {
    httpExchange.close();
    span.end(END_SPAN_OPTIONS);
  }
}
 
Example 3
Source File: CoreQueryManager.java    From heroic with Apache License 2.0 6 votes vote down vote up
private <T> AsyncFuture<T> run(
    final Function<ClusterNode.Group, AsyncFuture<T>> function,
    final Function<ClusterShard, Transform<Throwable, T>> catcher,
    final Collector<T, T> collector
) {
    final List<AsyncFuture<T>> futures = new ArrayList<>(shards.size());

    for (final ClusterShard shard : shards) {

        final Span span = tracer
            .spanBuilder("CoreQueryManager.run")
            .startSpan();

        span.putAttribute("shard", stringAttributeValue(shard.toString()));

        futures.add(shard
            .apply(function::apply, CoreQueryManager::retryTraceHandlerNoop)
            .catchFailed(catcher.apply(shard))
            .onFinished(span::end));
    }

    return async.collect(futures, collector);
}
 
Example 4
Source File: HelloWorldServer.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
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 5
Source File: SpanOperationsBenchmark.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
/** Add attributes individually. */
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public Span putAttribute(Data data) {
  Span span = data.attributeSpan;
  for (int i = 0; i < data.size; i++) {
    span.putAttribute(data.attributeKeys[i], data.attributeValues[i]);
  }
  return span;
}
 
Example 6
Source File: AbstractHttpHandler.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
void spanEnd(Span span, int httpStatus, @Nullable Throwable error) {
  if (span.getOptions().contains(Options.RECORD_EVENTS)) {
    span.putAttribute(
        HttpTraceAttributeConstants.HTTP_STATUS_CODE,
        AttributeValue.longAttributeValue(httpStatus));
    span.setStatus(HttpTraceUtil.parseResponseStatus(httpStatus, error));
  }
  span.end();
}
 
Example 7
Source File: GrpcOpenCensusInterceptor.java    From heroic with Apache License 2.0 5 votes vote down vote up
@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(
    final ServerCall<ReqT, RespT> call, final Metadata headers,
    final ServerCallHandler<ReqT, RespT> next) {

    final Span span = tracer.getCurrentSpan();
    span.putAttributes(environmentMetadata.toAttributes());
    span.putAttribute("protocol", stringAttributeValue("grpc"));
    span.putAttribute("span.kind", stringAttributeValue("server"));

    tracingConfig.getTags().forEach(
        (key, value) -> span.putAttribute(key, stringAttributeValue(value)));

    return next.startCall(call, headers);
}
 
Example 8
Source File: BigtableMutatorImpl.java    From heroic with Apache License 2.0 5 votes vote down vote up
private AsyncFuture<Void> mutateBatchRow(
    String tableName, ByteString rowKey, Mutations mutations
) {
    final Span span = tracer.spanBuilder("BigtableMutator.mutateBatchRow").startSpan();
    try (Scope ws = tracer.withSpan(span)) {
        span.putAttribute("table", AttributeValue.stringAttributeValue(tableName));

        final BulkMutation bulkMutation = getOrAddBulkMutation(tableName);

        span.addAnnotation("Adding rows to bulk mutation");
        return convertVoid(bulkMutation.add(toMutateRowRequest(tableName, rowKey, mutations)))
            .onFinished(span::end);
    }
}
 
Example 9
Source File: AbstractHttpHandler.java    From opencensus-java with Apache License 2.0 4 votes vote down vote up
private static void putAttributeIfNotEmptyOrNull(Span span, String key, @Nullable String value) {
  if (value != null && !value.isEmpty()) {
    span.putAttribute(key, AttributeValue.stringAttributeValue(value));
  }
}
 
Example 10
Source File: BigtableBackend.java    From heroic with Apache License 2.0 4 votes vote down vote up
private AsyncFuture<FetchData.Result> fetchBatch(
    final FetchQuotaWatcher watcher,
    final MetricType type,
    final List<PreparedQuery> prepared,
    final BigtableConnection c,
    final Consumer<MetricReadResult> metricsConsumer,
    final Span parentSpan
) {
    final BigtableDataClient client = c.getDataClient();

    final Span fetchBatchSpan =
        tracer.spanBuilderWithExplicitParent("bigtable.fetchBatch", parentSpan).startSpan();
    fetchBatchSpan.putAttribute("preparedQuerySize", longAttributeValue(prepared.size()));

    final List<AsyncFuture<FetchData.Result>> fetches = new ArrayList<>(prepared.size());

    for (final PreparedQuery p : prepared) {
        Span readRowsSpan = tracer.spanBuilderWithExplicitParent(
            "bigtable.readRows", fetchBatchSpan).startSpan();
        readRowsSpan.putAttribute("rowKeyBaseTimestamp", longAttributeValue(p.base));

        final Function<FlatRow.Cell, Metric> transform =
            cell -> p.deserialize(cell.getQualifier(), cell.getValue());

        QueryTrace.NamedWatch fs = QueryTrace.watch(FETCH_SEGMENT);

        final AsyncFuture<List<FlatRow>> readRows;
        try (Scope ignored = tracer.withSpan(fetchBatchSpan)) {
            readRows =
                client
                    .readRows(
                        table,
                        ReadRowsRequest.builder()
                            .range(new RowRange(
                                Optional.of(p.rowKeyStart), Optional.of(p.rowKeyEnd)))
                            .filter(
                                RowFilter.chain(
                                    Arrays.asList(
                                        RowFilter.newColumnRangeBuilder(p.columnFamily)
                                            .startQualifierOpen(p.startQualifierOpen)
                                            .endQualifierClosed(p.endQualifierClosed)
                                            .build(),
                                        RowFilter.onlyLatestCell())))
                            .build())
                    .onDone(new EndSpanFutureReporter(readRowsSpan));
        }

        final AtomicBoolean foundResourceIdentifier = new AtomicBoolean(false);
        fetches.add(readRows.directTransform(result -> {
            readRowsSpan.putAttribute("rowsReturned", longAttributeValue(result.size()));
            for (final FlatRow row : result) {
                SortedMap<String, String> resource = parseResourceFromRowKey(row.getRowKey());

                if (!foundResourceIdentifier.get() && resource.size() > 0) {
                    foundResourceIdentifier.set(true);
                }

                watcher.readData(row.getCells().size());

                final List<Metric> metrics = Lists.transform(row.getCells(), transform);
                final MetricCollection mc = MetricCollection.build(type, metrics);
                final MetricReadResult readResult = new MetricReadResult(mc, resource);

                metricsConsumer.accept(readResult);
            }

            readRowsSpan.putAttribute(
                "containsResourceIdentifier", booleanAttributeValue(
                    foundResourceIdentifier.get()));

            return new FetchData.Result(fs.end());
        }));
    }

    return async.collect(fetches, FetchData
        .collectResult(FETCH))
        .directTransform(result -> {
            fetchBatchSpan.end();
            // this is not actually how many rows were touched. The number of resource
            // identifiers are unknown until query time.
            watcher.accessedRows(prepared.size());
            return result;
        });
}
 
Example 11
Source File: HttpRequest.java    From google-http-java-client with Apache License 2.0 4 votes vote down vote up
private static void addSpanAttribute(Span span, String key, String value) {
  if (value != null) {
    span.putAttribute(key, AttributeValue.stringAttributeValue(value));
  }
}