io.opencensus.trace.AttributeValue Java Examples

The following examples show how to use io.opencensus.trace.AttributeValue. 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: 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 #2
Source File: RecordEventsSpanImpl.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
@Override
public void addAnnotation(String description, Map<String, AttributeValue> attributes) {
  Preconditions.checkNotNull(description, "description");
  Preconditions.checkNotNull(attributes, "attribute");
  synchronized (this) {
    if (hasBeenEnded) {
      logger.log(Level.FINE, "Calling addAnnotation() on an ended Span.");
      return;
    }
    getInitializedAnnotations()
        .addEvent(
            new EventWithNanoTime<Annotation>(
                clock.nowNanos(),
                Annotation.fromDescriptionAndAttributes(description, attributes)));
  }
}
 
Example #3
Source File: BasicDataBenchmark.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
private static AttributeValue[] getAttributeValues(int size, String attributeType) {
  AttributeValue[] attributeValues = new AttributeValue[size];
  switch (attributeType) {
    case "string":
      for (int i = 0; i < size; i++) {
        attributeValues[i] = AttributeValue.stringAttributeValue(ATTRIBUTE_VALUE_STRING + "-i");
      }
      break;
    case "boolean":
      for (int i = 0; i < size; i++) {
        attributeValues[i] = AttributeValue.booleanAttributeValue(i % 3 == 0);
      }
      break;
    case "long":
      for (int i = 0; i < size; i++) {
        attributeValues[i] = AttributeValue.longAttributeValue(ATTRIBUTE_VALUE_LONG + i);
      }
      break;
    default:
      throw new IllegalArgumentException("Unknown attribute type: " + attributeType);
  }
  return attributeValues;
}
 
Example #4
Source File: TracezZPageHandler.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
private static String renderAttributes(Map<String, AttributeValue> attributes) {
  StringBuilder stringBuilder = new StringBuilder();
  stringBuilder.append("Attributes:{");
  boolean first = true;
  for (Map.Entry<String, AttributeValue> entry : attributes.entrySet()) {
    if (first) {
      first = false;
      stringBuilder.append(entry.getKey());
      stringBuilder.append("=");
      stringBuilder.append(attributeValueToString(entry.getValue()));
    } else {
      stringBuilder.append(", ");
      stringBuilder.append(entry.getKey());
      stringBuilder.append("=");
      stringBuilder.append(attributeValueToString(entry.getValue()));
    }
  }
  stringBuilder.append("}");
  return stringBuilder.toString();
}
 
Example #5
Source File: JaegerExporterHandler.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
private static List<Tag> attributesToTags(
    final Map<String, AttributeValue> attributes, @Nullable final Tag extraTag) {
  final List<Tag> tags = Lists.newArrayListWithExpectedSize(attributes.size() + 1);
  for (final Map.Entry<String, AttributeValue> entry : attributes.entrySet()) {
    final Tag tag =
        entry
            .getValue()
            .match(
                stringAttributeConverter,
                booleanAttributeConverter,
                longAttributeConverter,
                doubleAttributeConverter,
                defaultAttributeConverter);
    tag.setKey(entry.getKey());
    tags.add(tag);
  }
  if (extraTag != null) {
    tags.add(extraTag);
  }
  return tags;
}
 
Example #6
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 #7
Source File: StackdriverTraceConfiguration.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
/**
 * Builds a {@link StackdriverTraceConfiguration}.
 *
 * @return a {@code StackdriverTraceConfiguration}.
 * @since 0.12
 */
public StackdriverTraceConfiguration build() {
  // Make a defensive copy of fixed attributes.
  setFixedAttributes(
      Collections.unmodifiableMap(
          new LinkedHashMap<String, AttributeValue>(getFixedAttributes())));
  Preconditions.checkArgument(
      !Strings.isNullOrEmpty(getProjectId()),
      "Cannot find a project ID from either configurations or application default.");
  for (Map.Entry<String, AttributeValue> fixedAttribute : getFixedAttributes().entrySet()) {
    Preconditions.checkNotNull(fixedAttribute.getKey(), "attribute key");
    Preconditions.checkNotNull(fixedAttribute.getValue(), "attribute value");
  }
  Preconditions.checkArgument(getDeadline().compareTo(ZERO) > 0, "Deadline must be positive.");
  return autoBuild();
}
 
Example #8
Source File: SpanDataTest.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
  attributesMap.put("MyAttributeKey1", AttributeValue.longAttributeValue(10));
  attributesMap.put("MyAttributeKey2", AttributeValue.booleanAttributeValue(true));
  attributes = Attributes.create(attributesMap, 1);
  annotationsList.add(SpanData.TimedEvent.create(eventTimestamp1, annotation));
  annotationsList.add(SpanData.TimedEvent.create(eventTimestamp3, annotation));
  annotations = TimedEvents.create(annotationsList, 2);
  networkEventsList.add(SpanData.TimedEvent.create(eventTimestamp1, recvNetworkEvent));
  networkEventsList.add(SpanData.TimedEvent.create(eventTimestamp2, sentNetworkEvent));
  networkEvents = TimedEvents.create(networkEventsList, 3);
  messageEventsList.add(SpanData.TimedEvent.create(eventTimestamp1, recvMessageEvent));
  messageEventsList.add(SpanData.TimedEvent.create(eventTimestamp2, sentMessageEvent));
  messageEvents = TimedEvents.create(messageEventsList, 3);
  linksList.add(Link.fromSpanContext(spanContext, Type.CHILD_LINKED_SPAN));
  links = Links.create(linksList, 0);
}
 
Example #9
Source File: OcAgentTraceExporterIntegrationTest.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
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 #10
Source File: RecordEventsSpanImpl.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Override
public void putAttribute(String key, AttributeValue value) {
  Preconditions.checkNotNull(key, "key");
  Preconditions.checkNotNull(value, "value");
  synchronized (this) {
    if (hasBeenEnded) {
      logger.log(Level.FINE, "Calling putAttributes() on an ended Span.");
      return;
    }
    getInitializedAttributes().putAttribute(key, value);
  }
}
 
Example #11
Source File: StackdriverTraceConfiguration.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a new {@link Builder}.
 *
 * @return a {@code Builder}.
 * @since 0.12
 */
public static Builder builder() {
  return new AutoValue_StackdriverTraceConfiguration.Builder()
      .setProjectId(DEFAULT_PROJECT_ID)
      .setFixedAttributes(Collections.<String, AttributeValue>emptyMap())
      .setDeadline(DEFAULT_DEADLINE);
}
 
Example #12
Source File: RecordEventsSpanImpl.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
/**
 * Returns an immutable representation of all the data from this {@code Span}.
 *
 * @return an immutable representation of all the data from this {@code Span}.
 * @throws IllegalStateException if the Span doesn't have RECORD_EVENTS option.
 */
public SpanData toSpanData() {
  synchronized (this) {
    SpanData.Attributes attributesSpanData =
        attributes == null
            ? SpanData.Attributes.create(Collections.<String, AttributeValue>emptyMap(), 0)
            : SpanData.Attributes.create(attributes, attributes.getNumberOfDroppedAttributes());
    SpanData.TimedEvents<Annotation> annotationsSpanData =
        createTimedEvents(getInitializedAnnotations(), timestampConverter);
    SpanData.TimedEvents<io.opencensus.trace.MessageEvent> messageEventsSpanData =
        createTimedEvents(getInitializedNetworkEvents(), timestampConverter);
    SpanData.Links linksSpanData =
        links == null
            ? SpanData.Links.create(Collections.<Link>emptyList(), 0)
            : SpanData.Links.create(
                new ArrayList<Link>(links.events), links.getNumberOfDroppedEvents());
    return SpanData.create(
        getContext(),
        parentSpanId,
        hasRemoteParent,
        name,
        kind,
        timestampConverter.convertNanoTime(startNanoTime),
        attributesSpanData,
        annotationsSpanData,
        messageEventsSpanData,
        linksSpanData,
        numberOfChildren,
        hasBeenEnded ? getStatusWithDefault() : null,
        hasBeenEnded ? timestampConverter.convertNanoTime(endNanoTime) : null);
  }
}
 
Example #13
Source File: BasicDataBenchmark.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
/** Create an AttributeMap. */
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public Map<String, AttributeValue> createAttributeMap(Data data) {
  Map<String, AttributeValue> attributeMap = new HashMap<>(data.size);
  for (int i = 0; i < data.size; i++) {
    attributeMap.put(data.attributeKeys[i], data.attributeValues[i]);
  }
  return attributeMap;
}
 
Example #14
Source File: BasicDataBenchmark.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
/** Create attribute values. */
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public AttributeValue[] createAttributeValues(Data data) {
  return getAttributeValues(data.size, data.attributeType);
}
 
Example #15
Source File: StackdriverV2ExporterHandlerExportTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
  MockitoAnnotations.initMocks(this);
  // TODO(@Hailong): TraceServiceClient.create(TraceServiceStub) is a beta API and might change
  // in the future.
  traceServiceClient = TraceServiceClient.create(traceServiceStub);
  handler =
      StackdriverV2ExporterHandler.createWithStub(
          PROJECT_ID, traceServiceClient, Collections.<String, AttributeValue>emptyMap());
}
 
Example #16
Source File: RecordTraceEventsBenchmark.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
/** This benchmark attempts to measure performance of adding an attribute to the span. */
@Benchmark
@BenchmarkMode(Mode.SampleTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public Span putAttribute(Data data) {
  data.span.putAttribute(ATTRIBUTE_KEY, AttributeValue.stringAttributeValue(ATTRIBUTE_VALUE));
  return data.span;
}
 
Example #17
Source File: StackdriverTraceConfigurationTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void disallowNullFixedAttributeKey() {
  StackdriverTraceConfiguration.Builder builder =
      StackdriverTraceConfiguration.builder().setProjectId("test");
  Map<String, AttributeValue> attributes =
      Collections.singletonMap(null, AttributeValue.stringAttributeValue("val"));
  builder.setFixedAttributes(attributes);
  thrown.expect(NullPointerException.class);
  builder.build();
}
 
Example #18
Source File: TelemetryUtils.java    From meghanada-server with GNU General Public License v3.0 5 votes vote down vote up
public static void setStatusINTERNAL(String message) {
  // add error info annotation
  Span current = tracer.getCurrentSpan();
  current.addAnnotation(getBaseAnnotation());
  HashMap<String, AttributeValue> newMap = new HashMap<>(javaAttributeMap);
  newMap.put("java.vm.memory", AttributeValue.stringAttributeValue(Config.getMemoryString()));
  Annotation vmAnno = Annotation.fromDescriptionAndAttributes("java.vm properties", newMap);
  current.addAnnotation(vmAnno);
  Annotation osAnno = Annotation.fromDescriptionAndAttributes("os properties", osAttributeMap);
  current.addAnnotation(osAnno);
  TelemetryUtils.setStatus(Status.INTERNAL.withDescription(message));
}
 
Example #19
Source File: TelemetryUtils.java    From meghanada-server with GNU General Public License v3.0 5 votes vote down vote up
ParentSpan(Span span, String name) {
  this.span = span;
  this.span.putAttributes(attrs);
  attrs.put("http.method", AttributeValue.stringAttributeValue("GET"));
  attrs.put("http.path", AttributeValue.stringAttributeValue(name));
  attrs.put("http.user_agent", AttributeValue.stringAttributeValue(TelemetryUtils.getUID()));
  attrs.put("http.status_code", AttributeValue.longAttributeValue(500));
}
 
Example #20
Source File: JaegerExporterHandlerTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
private static SpanData.TimedEvent<Annotation> sampleAnnotation() {
  return SpanData.TimedEvent.create(
      Timestamp.create(1519629872L, 987654321),
      Annotation.fromDescriptionAndAttributes(
          "annotation #1",
          ImmutableMap.of(
              "bool", AttributeValue.booleanAttributeValue(true),
              "long", AttributeValue.longAttributeValue(1337L),
              "string",
                  AttributeValue.stringAttributeValue(
                      "Kind words do not cost much. Yet they accomplish much. -- Pascal"))));
}
 
Example #21
Source File: InstanaExporterHandler.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@javax.annotation.Nullable
private static String attributeValueToString(AttributeValue attributeValue) {
  return attributeValue.match(
      returnToString,
      returnToString,
      returnToString,
      returnToString,
      Functions.</*@Nullable*/ String>returnNull());
}
 
Example #22
Source File: ZipkinExporterHandler.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("nullness")
private static String attributeValueToString(AttributeValue attributeValue) {
  return attributeValue.match(
      returnToString,
      returnToString,
      returnToString,
      returnToString,
      Functions.<String>returnConstant(""));
}
 
Example #23
Source File: DatadogExporterHandler.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
private static String attributeValueToString(AttributeValue attributeValue) {
  return attributeValue.match(
      Functions.returnToString(),
      Functions.returnToString(),
      Functions.returnToString(),
      Functions.returnToString(),
      Functions.throwIllegalArgumentException());
}
 
Example #24
Source File: RecordEventsSpanImplTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
  MockitoAnnotations.initMocks(this);
  attributes.put(
      "MyStringAttributeKey", AttributeValue.stringAttributeValue("MyStringAttributeValue"));
  attributes.put("MyLongAttributeKey", AttributeValue.longAttributeValue(123L));
  attributes.put("MyBooleanAttributeKey", AttributeValue.booleanAttributeValue(false));
  expectedAttributes.putAll(attributes);
  expectedAttributes.put(
      "MySingleStringAttributeKey",
      AttributeValue.stringAttributeValue("MySingleStringAttributeValue"));
}
 
Example #25
Source File: RecordEventsSpanImplTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void noEventsRecordedAfterEnd() {
  RecordEventsSpanImpl span =
      RecordEventsSpanImpl.startSpan(
          spanContext,
          SPAN_NAME,
          null,
          parentSpanId,
          false,
          TraceParams.DEFAULT,
          startEndHandler,
          timestampConverter,
          testClock);
  span.end();
  // Check that adding trace events after Span#end() does not throw any exception and are not
  // recorded.
  span.putAttributes(attributes);
  span.putAttribute(
      "MySingleStringAttributeKey",
      AttributeValue.stringAttributeValue("MySingleStringAttributeValue"));
  span.addAnnotation(Annotation.fromDescription(ANNOTATION_DESCRIPTION));
  span.addAnnotation(ANNOTATION_DESCRIPTION, attributes);
  span.addNetworkEvent(
      NetworkEvent.builder(NetworkEvent.Type.RECV, 1).setUncompressedMessageSize(3).build());
  span.addLink(Link.fromSpanContext(spanContext, Link.Type.CHILD_LINKED_SPAN));
  SpanData spanData = span.toSpanData();
  assertThat(spanData.getStartTimestamp()).isEqualTo(timestamp);
  assertThat(spanData.getAttributes().getAttributeMap()).isEmpty();
  assertThat(spanData.getAnnotations().getEvents()).isEmpty();
  assertThat(spanData.getNetworkEvents().getEvents()).isEmpty();
  assertThat(spanData.getLinks().getLinks()).isEmpty();
  assertThat(spanData.getStatus()).isEqualTo(Status.OK);
  assertThat(spanData.getEndTimestamp()).isEqualTo(timestamp);
}
 
Example #26
Source File: AbstractHttpHandlerTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void handleEndWithRecordEvents() {
  when(extractor.getStatusCode(any(Object.class))).thenReturn(0);
  handler.spanEnd(fakeSpan, 0, error);
  verify(fakeSpan)
      .putAttribute(eq(HttpTraceAttributeConstants.HTTP_STATUS_CODE), attributeCaptor.capture());
  assertThat(attributeCaptor.getValue()).isEqualTo(AttributeValue.longAttributeValue(0));
}
 
Example #27
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 #28
Source File: JsonConversionUtils.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Nullable
@SuppressWarnings("nullness")
private static String attributeValueToString(AttributeValue attributeValue) {
  return attributeValue.match(
      Functions.returnToString(),
      Functions.returnToString(),
      Functions.returnToString(),
      Functions.returnToString(),
      Functions.returnConstant(""));
}
 
Example #29
Source File: JaegerExporterHandlerTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void convertErrorSpanDataToJaegerThriftSpan() throws SenderException {
  long startTime = 1519629870001L;
  long endTime = 1519630148002L;
  String statusMessage = "timeout";
  SpanData spanData =
      SpanData.create(
          sampleSpanContext(),
          SpanId.fromBytes(new byte[] {(byte) 0x7F, FF, FF, FF, FF, FF, FF, FF}),
          true,
          "test",
          Kind.SERVER,
          Timestamp.fromMillis(startTime),
          SpanData.Attributes.create(Collections.<String, AttributeValue>emptyMap(), 0),
          SpanData.TimedEvents.create(Collections.<TimedEvent<Annotation>>emptyList(), 0),
          SpanData.TimedEvents.create(Collections.<TimedEvent<MessageEvent>>emptyList(), 0),
          SpanData.Links.create(Collections.<Link>emptyList(), 0),
          0,
          Status.DEADLINE_EXCEEDED.withDescription(statusMessage),
          Timestamp.fromMillis(endTime));

  handler.export(singletonList(spanData));

  verify(mockSender).send(eq(process), captor.capture());
  List<Span> spans = captor.getValue();

  assertThat(spans.size()).isEqualTo(1);
  Span span = spans.get(0);

  assertThat(span.tags.size()).isEqualTo(3);
  assertThat(span.tags)
      .containsExactly(
          new Tag(JaegerExporterHandler.SPAN_KIND, TagType.STRING).setVStr("server"),
          new Tag(JaegerExporterHandler.STATUS_CODE, TagType.LONG).setVLong(4),
          new Tag(JaegerExporterHandler.STATUS_MESSAGE, TagType.STRING).setVStr(statusMessage));
}
 
Example #30
Source File: StackdriverTraceConfigurationTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void disallowNullFixedAttributeValue() {
  StackdriverTraceConfiguration.Builder builder =
      StackdriverTraceConfiguration.builder().setProjectId("test");
  Map<String, AttributeValue> attributes = Collections.singletonMap("key", null);
  builder.setFixedAttributes(attributes);
  thrown.expect(NullPointerException.class);
  builder.build();
}