io.opencensus.trace.SpanId Java Examples

The following examples show how to use io.opencensus.trace.SpanId. 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: OpenCensusTraceLoggingEnhancerTest.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
@Test
public void enhanceLogEntry_AddSampledSpanToLogEntry() {
  LogEntry logEntry =
      getEnhancedLogEntry(
          new OpenCensusTraceLoggingEnhancer("my-test-project-3"),
          new TestSpan(
              SpanContext.create(
                  TraceId.fromLowerBase16("4c6af40c499951eb7de2777ba1e4fefa"),
                  SpanId.fromLowerBase16("de52e84d13dd232d"),
                  TraceOptions.builder().setIsSampled(true).build(),
                  EMPTY_TRACESTATE)));
  assertTrue(logEntry.getTraceSampled());
  assertThat(logEntry.getTrace())
      .isEqualTo("projects/my-test-project-3/traces/4c6af40c499951eb7de2777ba1e4fefa");
  assertThat(logEntry.getSpanId()).isEqualTo("de52e84d13dd232d");
}
 
Example #2
Source File: SamplersTest.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
private static void assertSamplerSamplesWithProbability(
    Sampler sampler, SpanContext parent, List<Span> parentLinks, double probability) {
  Random random = new Random(1234);
  int count = 0; // Count of spans with sampling enabled
  for (int i = 0; i < NUM_SAMPLE_TRIES; i++) {
    if (sampler.shouldSample(
        parent,
        false,
        TraceId.generateRandomId(random),
        SpanId.generateRandomId(random),
        SPAN_NAME,
        parentLinks)) {
      count++;
    }
  }
  double proportionSampled = (double) count / NUM_SAMPLE_TRIES;
  // Allow for a large amount of slop (+/- 10%) in number of sampled traces, to avoid flakiness.
  assertThat(proportionSampled < probability + 0.1 && proportionSampled > probability - 0.1)
      .isTrue();
}
 
Example #3
Source File: JaegerExporterHandlerTest.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
private static List<Link> sampleLinks() {
  return Lists.newArrayList(
      Link.fromSpanContext(
          SpanContext.create(
              TraceId.fromBytes(
                  new byte[] {FF, FF, FF, FF, FF, FF, FF, FF, FF, FF, FF, FF, FF, FF, FF, 0}),
              SpanId.fromBytes(new byte[] {0, 0, 0, 0, 0, 0, 2, 0}),
              TraceOptions.builder().setIsSampled(false).build(),
              Tracestate.builder().build()),
          Link.Type.CHILD_LINKED_SPAN,
          ImmutableMap.of(
              "Bool", AttributeValue.booleanAttributeValue(true),
              "Long", AttributeValue.longAttributeValue(299792458L),
              "String",
                  AttributeValue.stringAttributeValue(
                      "Man is condemned to be free; because once thrown into the world, "
                          + "he is responsible for everything he does. -- Sartre"))));
}
 
Example #4
Source File: TextFormatGetterTest.java    From heroic with Apache License 2.0 6 votes vote down vote up
@Test
public void testSpan () throws Exception {

  Random random = new Random(1234);
  SpanId generateSpanId = SpanId.generateRandomId(random);
  String spanId = UnsignedLongs.toString(spanIdToLong(generateSpanId));
  String traceId = TraceId.generateRandomId(random).toLowerBase16();

  final List<String> headers = new ArrayList<>();
  headers.add(traceId + "/" + spanId + ";o=1");
  doReturn(headers).when(request).getRequestHeader("X-Cloud-Trace-Context");

  final SpanContext spanContext = textFormat.extract(request, textFormatGetter);

  assertEquals(generateSpanId, spanContext.getSpanId());
}
 
Example #5
Source File: SpanOperationsBenchmark.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
private void initAttributes() {
  attributeValues = createAttributeValues(size);
  attributeKeys = new String[size];
  attributeMap = new HashMap<>(size);
  messageEvents = new MessageEvent[size];
  links = new Link[size];
  for (int i = 0; i < size; i++) {
    attributeKeys[i] = ATTRIBUTE_KEY + "-i";
    attributeMap.put(attributeKeys[i], attributeValues[i]);
    messageEvents[i] = MessageEvent.builder(MessageEvent.Type.SENT, MESSAGE_ID + i).build();
    links[i] =
        Link.fromSpanContext(
            SpanContext.create(
                TraceId.fromBytes(
                    new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, (byte) i}),
                SpanId.fromBytes(new byte[] {1, 2, 3, 4, 5, 6, 7, (byte) i}),
                TraceOptions.DEFAULT,
                TRACESTATE_DEFAULT),
            Link.Type.PARENT_LINKED_SPAN);
  }
}
 
Example #6
Source File: JsonConversionUtilsTest.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
  SpanData spanData =
      SpanData.create(
          SpanContext.create(
              TraceId.fromLowerBase16(SAMPLE_TRACE_ID),
              SpanId.fromLowerBase16(SAMPLE_SPAN_ID),
              SAMPLE_TRACE_OPTION,
              SAMPLE_TRACE_STATE),
          SpanId.fromLowerBase16(SAMPLE_PARENT_SPAN_ID),
          true,
          "SpanName",
          null,
          Timestamp.create(155196336, 194009601),
          Attributes.create(attributes, 0),
          TimedEvents.create(annotations, 0),
          TimedEvents.create(messageEvents, 0),
          Links.create(Collections.<Link>emptyList(), 0),
          null,
          Status.OK,
          Timestamp.create(155296336, 465726528));

  spanDataList = new ArrayList<SpanData>();
  spanDataList.add(spanData);
}
 
Example #7
Source File: RecordEventsSpanImpl.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
private RecordEventsSpanImpl(
    SpanContext context,
    String name,
    @Nullable Kind kind,
    @Nullable SpanId parentSpanId,
    @Nullable Boolean hasRemoteParent,
    TraceParams traceParams,
    StartEndHandler startEndHandler,
    @Nullable TimestampConverter timestampConverter,
    Clock clock) {
  super(context, RECORD_EVENTS_SPAN_OPTIONS);
  this.parentSpanId = parentSpanId;
  this.hasRemoteParent = hasRemoteParent;
  this.name = name;
  this.kind = kind;
  this.traceParams = traceParams;
  this.startEndHandler = startEndHandler;
  this.clock = clock;
  this.hasBeenEnded = false;
  this.sampleToLocalSpanStore = false;
  this.numberOfChildren = 0;
  this.timestampConverter =
      timestampConverter != null ? timestampConverter : TimestampConverter.now(clock);
  startNanoTime = clock.nowNanos();
}
 
Example #8
Source File: InstanaExporterHandlerTest.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
@Test
public void generateSpan_NullStatus() {
  SpanData data =
      SpanData.create(
          SpanContext.create(
              TraceId.fromLowerBase16(TRACE_ID),
              SpanId.fromLowerBase16(SPAN_ID),
              TraceOptions.builder().setIsSampled(true).build()),
          SpanId.fromLowerBase16(PARENT_SPAN_ID),
          true, /* hasRemoteParent */
          "SpanName", /* name */
          null, /* kind */
          Timestamp.create(1505855794, 194009601) /* startTimestamp */,
          Attributes.create(attributes, 0 /* droppedAttributesCount */),
          TimedEvents.create(annotations, 0 /* droppedEventsCount */),
          TimedEvents.create(messageEvents, 0 /* droppedEventsCount */),
          Links.create(Collections.<Link>emptyList(), 0 /* droppedLinksCount */),
          null, /* childSpanCount */
          null, /* status */
          Timestamp.create(1505855799, 465726528) /* endTimestamp */);

  assertThat(InstanaExporterHandler.convertToJson(Collections.singletonList(data)))
      .isEqualTo("[]");
}
 
Example #9
Source File: InProcessRunningSpanStoreImplTest.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
private RecordEventsSpanImpl createSpan(String spanName) {
  final SpanContext spanContext =
      SpanContext.create(
          TraceId.generateRandomId(random),
          SpanId.generateRandomId(random),
          TraceOptions.DEFAULT,
          Tracestate.builder().build());
  return RecordEventsSpanImpl.startSpan(
      spanContext,
      spanName,
      null,
      SpanId.generateRandomId(random),
      false,
      TraceParams.DEFAULT,
      startEndHandler,
      null,
      MillisClock.getInstance());
}
 
Example #10
Source File: AppEngineCloudTraceContextUtils.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
/**
 * Converts AppEngine {@code CloudTraceContext} to {@code SpanContext}.
 *
 * @param cloudTraceContext the AppEngine {@code CloudTraceContext}.
 * @return the converted {@code SpanContext}.
 * @since 0.14
 */
public static SpanContext fromCloudTraceContext(CloudTraceContext cloudTraceContext) {
  checkNotNull(cloudTraceContext, "cloudTraceContext");

  try {
    // Extract the trace ID from the binary protobuf CloudTraceContext#traceId.
    TraceIdProto traceIdProto = TraceIdProto.parseFrom(cloudTraceContext.getTraceId());
    ByteBuffer traceIdBuf = ByteBuffer.allocate(TraceId.SIZE);
    traceIdBuf.putLong(traceIdProto.getHi());
    traceIdBuf.putLong(traceIdProto.getLo());
    ByteBuffer spanIdBuf = ByteBuffer.allocate(SpanId.SIZE);
    spanIdBuf.putLong(cloudTraceContext.getSpanId());

    return SpanContext.create(
        TraceId.fromBytes(traceIdBuf.array()),
        SpanId.fromBytes(spanIdBuf.array()),
        TraceOptions.builder().setIsSampled(cloudTraceContext.isTraceEnabled()).build(),
        TRACESTATE_DEFAULT);
  } catch (com.google.protobuf.InvalidProtocolBufferException e) {
    throw new RuntimeException(e);
  }
}
 
Example #11
Source File: OpenCensusLog4jLogCorrelationTest.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
@Test
public void preserveOtherKeyValuePairs() {
  String log =
      logWithSpanAndLog4jConfiguration(
          "%X{traceId} %X{myTestKey} %-5level - %msg",
          SpanContext.create(
              TraceId.fromLowerBase16("c95329bb6b7de41afbc51a231c128f97"),
              SpanId.fromLowerBase16("bf22ea74d38eddad"),
              TraceOptions.builder().setIsSampled(true).build(),
              EMPTY_TRACESTATE),
          new Function<Logger, Void>() {
            @Override
            public Void apply(Logger logger) {
              String key = "myTestKey";
              ThreadContext.put(key, "myTestValue");
              try {
                logger.error("message #4");
              } finally {
                ThreadContext.remove(key);
              }
              return null;
            }
          });
  assertThat(log).isEqualTo("c95329bb6b7de41afbc51a231c128f97 myTestValue ERROR - message #4");
}
 
Example #12
Source File: SpanBuilderImplTest.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
@Test
public void startRemoteSpan() {
  SpanContext spanContext =
      SpanContext.create(
          TraceId.generateRandomId(randomHandler.current()),
          SpanId.generateRandomId(randomHandler.current()),
          TraceOptions.DEFAULT);
  RecordEventsSpanImpl span =
      (RecordEventsSpanImpl)
          SpanBuilderImpl.createWithRemoteParent(SPAN_NAME, spanContext, spanBuilderOptions)
              .setRecordEvents(true)
              .startSpan();
  assertThat(span.getContext().isValid()).isTrue();
  assertThat(span.getContext().getTraceId()).isEqualTo(spanContext.getTraceId());
  assertThat(span.getContext().getTraceOptions().isSampled()).isTrue();
  SpanData spanData = span.toSpanData();
  assertThat(spanData.getParentSpanId()).isEqualTo(spanContext.getSpanId());
  assertThat(spanData.getHasRemoteParent()).isTrue();
}
 
Example #13
Source File: OpenCensusLog4jLogCorrelationTest.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
@Test
public void addNonSampledSpanToLogEntryWithAllSpans() {
  String log =
      logWithSpanAndLog4jConfiguration(
          TEST_PATTERN,
          SpanContext.create(
              TraceId.fromLowerBase16("cd7061dfa9d312cdcc42edab3feab51b"),
              SpanId.fromLowerBase16("117d42d4c7acd066"),
              TraceOptions.builder().setIsSampled(false).build(),
              EMPTY_TRACESTATE),
          new Function<Logger, Void>() {
            @Override
            public Void apply(Logger logger) {
              logger.info("message #2");
              return null;
            }
          });
  assertThat(log)
      .isEqualTo(
          "traceId=cd7061dfa9d312cdcc42edab3feab51b spanId=117d42d4c7acd066 sampled=false INFO  "
              + "- message #2");
}
 
Example #14
Source File: OpenCensusLog4jLogCorrelationTest.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
@Test
public void addSampledSpanToLogEntryWithAllSpans() {
  String log =
      logWithSpanAndLog4jConfiguration(
          TEST_PATTERN,
          SpanContext.create(
              TraceId.fromLowerBase16("b9718fe3d82d36fce0e6a1ada1c21db0"),
              SpanId.fromLowerBase16("75159dde8c503fee"),
              TraceOptions.builder().setIsSampled(true).build(),
              EMPTY_TRACESTATE),
          new Function<Logger, Void>() {
            @Override
            public Void apply(Logger logger) {
              logger.warn("message #1");
              return null;
            }
          });
  assertThat(log)
      .isEqualTo(
          "traceId=b9718fe3d82d36fce0e6a1ada1c21db0 spanId=75159dde8c503fee "
              + "sampled=true WARN  - message #1");
}
 
Example #15
Source File: OpenCensusTraceLoggingEnhancerTest.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
@Test
public void enhanceLogEntry_AddNonSampledSpanToLogEntry() {
  LogEntry logEntry =
      getEnhancedLogEntry(
          new OpenCensusTraceLoggingEnhancer("my-test-project-6"),
          new TestSpan(
              SpanContext.create(
                  TraceId.fromLowerBase16("72c905c76f99e99974afd84dc053a480"),
                  SpanId.fromLowerBase16("731e102335b7a5a0"),
                  TraceOptions.builder().setIsSampled(false).build(),
                  EMPTY_TRACESTATE)));
  assertFalse(logEntry.getTraceSampled());
  assertThat(logEntry.getTrace())
      .isEqualTo("projects/my-test-project-6/traces/72c905c76f99e99974afd84dc053a480");
  assertThat(logEntry.getSpanId()).isEqualTo("731e102335b7a5a0");
}
 
Example #16
Source File: SpanBuilderImpl.java    From opencensus-java with Apache License 2.0 6 votes vote down vote up
private static boolean makeSamplingDecision(
    @Nullable SpanContext parent,
    @Nullable Boolean hasRemoteParent,
    String name,
    @Nullable Sampler sampler,
    List<Span> parentLinks,
    TraceId traceId,
    SpanId spanId,
    TraceParams activeTraceParams) {
  // If users set a specific sampler in the SpanBuilder, use it.
  if (sampler != null) {
    return sampler.shouldSample(parent, hasRemoteParent, traceId, spanId, name, parentLinks);
  }
  // Use the default sampler if this is a root Span or this is an entry point Span (has remote
  // parent).
  if (Boolean.TRUE.equals(hasRemoteParent) || parent == null || !parent.isValid()) {
    return activeTraceParams
        .getSampler()
        .shouldSample(parent, hasRemoteParent, traceId, spanId, name, parentLinks);
  }
  // Parent is always different than null because otherwise we use the default sampler.
  return parent.getTraceOptions().isSampled() || isAnyParentLinkSampled(parentLinks);
}
 
Example #17
Source File: InstanaExporterHandlerTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void generateSpan_NoKindAndRemoteParent() {
  SpanData data =
      SpanData.create(
          SpanContext.create(
              TraceId.fromLowerBase16(TRACE_ID),
              SpanId.fromLowerBase16(SPAN_ID),
              TraceOptions.builder().setIsSampled(true).build()),
          SpanId.fromLowerBase16(PARENT_SPAN_ID),
          true, /* hasRemoteParent */
          "SpanName", /* name */
          null, /* kind */
          Timestamp.create(1505855794, 194009601) /* startTimestamp */,
          Attributes.create(attributes, 0 /* droppedAttributesCount */),
          TimedEvents.create(annotations, 0 /* droppedEventsCount */),
          TimedEvents.create(messageEvents, 0 /* droppedEventsCount */),
          Links.create(Collections.<Link>emptyList(), 0 /* droppedLinksCount */),
          null, /* childSpanCount */
          Status.OK,
          Timestamp.create(1505855799, 465726528) /* endTimestamp */);

  assertThat(InstanaExporterHandler.convertToJson(Collections.singletonList(data)))
      .isEqualTo(
          "["
              + "{"
              + "\"spanId\":\"9cc1e3049173be09\","
              + "\"traceId\":\"d239036e7d5cec11\","
              + "\"parentId\":\"8b03ab423da481c5\","
              + "\"timestamp\":1505855794194,"
              + "\"duration\":5271,"
              + "\"name\":\"SpanName\","
              + "\"type\":\"ENTRY\","
              + "\"data\":"
              + "{\"http.url\":\"http://localhost/foo\"}"
              + "}"
              + "]");
}
 
Example #18
Source File: InstanaExporterHandlerTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void generateSpan_ServerKind() {
  SpanData data =
      SpanData.create(
          SpanContext.create(
              TraceId.fromLowerBase16(TRACE_ID),
              SpanId.fromLowerBase16(SPAN_ID),
              TraceOptions.builder().setIsSampled(true).build()),
          SpanId.fromLowerBase16(PARENT_SPAN_ID),
          true, /* hasRemoteParent */
          "SpanName", /* name */
          Kind.SERVER, /* kind */
          Timestamp.create(1505855794, 194009601) /* startTimestamp */,
          Attributes.create(attributes, 0 /* droppedAttributesCount */),
          TimedEvents.create(annotations, 0 /* droppedEventsCount */),
          TimedEvents.create(messageEvents, 0 /* droppedEventsCount */),
          Links.create(Collections.<Link>emptyList(), 0 /* droppedLinksCount */),
          null, /* childSpanCount */
          Status.OK,
          Timestamp.create(1505855799, 465726528) /* endTimestamp */);

  assertThat(InstanaExporterHandler.convertToJson(Collections.singletonList(data)))
      .isEqualTo(
          "["
              + "{"
              + "\"spanId\":\"9cc1e3049173be09\","
              + "\"traceId\":\"d239036e7d5cec11\","
              + "\"parentId\":\"8b03ab423da481c5\","
              + "\"timestamp\":1505855794194,"
              + "\"duration\":5271,"
              + "\"name\":\"SpanName\","
              + "\"type\":\"ENTRY\","
              + "\"data\":"
              + "{\"http.url\":\"http://localhost/foo\"}"
              + "}"
              + "]");
}
 
Example #19
Source File: StatsTestUtils.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a MockableSpan with a random trace ID and span ID.
 */
@SuppressWarnings("deprecation")
public static MockableSpan generateRandomSpan(Random random) {
  return new MockableSpan(
      SpanContext.create(
          TraceId.generateRandomId(random),
          SpanId.generateRandomId(random),
          TraceOptions.DEFAULT),
      null);
}
 
Example #20
Source File: InstanaExporterHandlerTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void generateSpan_ErrorStatus() {
  SpanData data =
      SpanData.create(
          SpanContext.create(
              TraceId.fromLowerBase16(TRACE_ID),
              SpanId.fromLowerBase16(SPAN_ID),
              TraceOptions.builder().setIsSampled(true).build()),
          SpanId.fromLowerBase16(PARENT_SPAN_ID),
          true, /* hasRemoteParent */
          "SpanName", /* name */
          Kind.CLIENT, /* kind */
          Timestamp.create(1505855794, 194009601) /* startTimestamp */,
          Attributes.create(attributes, 0 /* droppedAttributesCount */),
          TimedEvents.create(annotations, 0 /* droppedEventsCount */),
          TimedEvents.create(messageEvents, 0 /* droppedEventsCount */),
          Links.create(Collections.<Link>emptyList(), 0 /* droppedLinksCount */),
          null, /* childSpanCount */
          Status.OUT_OF_RANGE, /* status, any but OK */
          Timestamp.create(1505855799, 465726528) /* endTimestamp */);

  assertThat(InstanaExporterHandler.convertToJson(Collections.singletonList(data)))
      .isEqualTo(
          "["
              + "{"
              + "\"spanId\":\"9cc1e3049173be09\","
              + "\"traceId\":\"d239036e7d5cec11\","
              + "\"parentId\":\"8b03ab423da481c5\","
              + "\"timestamp\":1505855794194,"
              + "\"duration\":5271,"
              + "\"name\":\"SpanName\","
              + "\"type\":\"EXIT\","
              + "\"error\":true,"
              + "\"data\":"
              + "{\"http.url\":\"http://localhost/foo\"}"
              + "}"
              + "]");
}
 
Example #21
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 #22
Source File: JaegerExporterHandlerTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
private static SpanContext sampleSpanContext() {
  return SpanContext.create(
      TraceId.fromBytes(new byte[] {FF, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}),
      SpanId.fromBytes(new byte[] {0, 0, 0, 0, 0, 0, 1, 0}),
      TraceOptions.builder().setIsSampled(true).build(),
      Tracestate.builder().build());
}
 
Example #23
Source File: OpenCensusTraceContextDataInjectorTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@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 #24
Source File: OpenCensusLog4jLogCorrelationTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void overwriteExistingTracingKey() {
  String log =
      logWithSpanAndLog4jConfiguration(
          TEST_PATTERN,
          SpanContext.create(
              TraceId.fromLowerBase16("18e4ae44273a0c44e0c9ea4380792c66"),
              SpanId.fromLowerBase16("199a7e16daa000a7"),
              TraceOptions.builder().setIsSampled(true).build(),
              EMPTY_TRACESTATE),
          new Function<Logger, Void>() {
            @Override
            public Void apply(Logger logger) {
              ThreadContext.put(
                  OpenCensusTraceContextDataInjector.TRACE_ID_CONTEXT_KEY, "existingTraceId");
              try {
                logger.error("message #5");
              } finally {
                ThreadContext.remove(OpenCensusTraceContextDataInjector.TRACE_ID_CONTEXT_KEY);
              }
              return null;
            }
          });
  assertThat(log)
      .isEqualTo(
          "traceId=18e4ae44273a0c44e0c9ea4380792c66 spanId=199a7e16daa000a7 "
              + "sampled=true ERROR - message #5");
}
 
Example #25
Source File: ZipkinExporterHandlerTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void generateSpan_ServerKind() {
  SpanData data =
      SpanData.create(
          SpanContext.create(
              TraceId.fromLowerBase16(TRACE_ID),
              SpanId.fromLowerBase16(SPAN_ID),
              TraceOptions.builder().setIsSampled(true).build()),
          // TODO SpanId.fromLowerBase16
          SpanId.fromLowerBase16(PARENT_SPAN_ID),
          true, /* hasRemoteParent */
          "Recv.helloworld.Greeter.SayHello", /* name */
          Kind.SERVER, /* kind */
          Timestamp.create(1505855794, 194009601) /* startTimestamp */,
          Attributes.create(attributes, 0 /* droppedAttributesCount */),
          TimedEvents.create(annotations, 0 /* droppedEventsCount */),
          TimedEvents.create(messageEvents, 0 /* droppedEventsCount */),
          Links.create(Collections.<Link>emptyList(), 0 /* droppedLinksCount */),
          null, /* childSpanCount */
          Status.OK,
          Timestamp.create(1505855799, 465726528) /* endTimestamp */);

  assertThat(ZipkinExporterHandler.generateSpan(data, localEndpoint))
      .isEqualTo(
          Span.newBuilder()
              .traceId(TRACE_ID)
              .parentId(PARENT_SPAN_ID)
              .id(SPAN_ID)
              .kind(Span.Kind.SERVER)
              .name(data.getName())
              .timestamp(1505855794000000L + 194009601L / 1000)
              .duration(
                  (1505855799000000L + 465726528L / 1000)
                      - (1505855794000000L + 194009601L / 1000))
              .localEndpoint(localEndpoint)
              .addAnnotation(1505855799000000L + 433901068L / 1000, "RECEIVED")
              .addAnnotation(1505855799000000L + 459486280L / 1000, "SENT")
              .putTag(ZipkinExporterHandler.STATUS_CODE, "OK")
              .build());
}
 
Example #26
Source File: ZipkinExporterHandlerTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void generateSpan_ClientKind() {
  SpanData data =
      SpanData.create(
          SpanContext.create(
              TraceId.fromLowerBase16(TRACE_ID),
              SpanId.fromLowerBase16(SPAN_ID),
              TraceOptions.builder().setIsSampled(true).build()),
          // TODO SpanId.fromLowerBase16
          SpanId.fromLowerBase16(PARENT_SPAN_ID),
          true, /* hasRemoteParent */
          "Sent.helloworld.Greeter.SayHello", /* name */
          Kind.CLIENT, /* kind */
          Timestamp.create(1505855794, 194009601) /* startTimestamp */,
          Attributes.create(attributes, 0 /* droppedAttributesCount */),
          TimedEvents.create(annotations, 0 /* droppedEventsCount */),
          TimedEvents.create(messageEvents, 0 /* droppedEventsCount */),
          Links.create(Collections.<Link>emptyList(), 0 /* droppedLinksCount */),
          null, /* childSpanCount */
          Status.OK,
          Timestamp.create(1505855799, 465726528) /* endTimestamp */);

  assertThat(ZipkinExporterHandler.generateSpan(data, localEndpoint))
      .isEqualTo(
          Span.newBuilder()
              .traceId(TRACE_ID)
              .parentId(PARENT_SPAN_ID)
              .id(SPAN_ID)
              .kind(Span.Kind.CLIENT)
              .name(data.getName())
              .timestamp(1505855794000000L + 194009601L / 1000)
              .duration(
                  (1505855799000000L + 465726528L / 1000)
                      - (1505855794000000L + 194009601L / 1000))
              .localEndpoint(localEndpoint)
              .addAnnotation(1505855799000000L + 433901068L / 1000, "RECEIVED")
              .addAnnotation(1505855799000000L + 459486280L / 1000, "SENT")
              .putTag(ZipkinExporterHandler.STATUS_CODE, "OK")
              .build());
}
 
Example #27
Source File: DatadogExporterHandler.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
private static long convertSpanId(final SpanId spanId) {
  final byte[] bytes = spanId.getBytes();
  long result = 0;
  for (int i = 0; i < Long.SIZE / Byte.SIZE; i++) {
    result <<= Byte.SIZE;
    result |= (bytes[i] & 0xff);
  }
  if (result < 0) {
    return -result;
  }
  return result;
}
 
Example #28
Source File: OpenCensusTraceLoggingEnhancerTest.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
@Test
public void enhanceLogEntry_ConvertNullProjectIdToEmptyString() {
  LogEntry logEntry =
      getEnhancedLogEntry(
          new OpenCensusTraceLoggingEnhancer(null),
          new TestSpan(
              SpanContext.create(
                  TraceId.fromLowerBase16("bfb4248a24325a905873a1d43001d9a0"),
                  SpanId.fromLowerBase16("6f23f9afd448e272"),
                  TraceOptions.builder().setIsSampled(true).build(),
                  EMPTY_TRACESTATE)));
  assertThat(logEntry.getTrace()).isEqualTo("projects//traces/bfb4248a24325a905873a1d43001d9a0");
}
 
Example #29
Source File: JaegerExporterHandler.java    From opencensus-java with Apache License 2.0 5 votes vote down vote up
private long spanIdToLong(final @Nullable SpanId spanId) {
  if (spanId == null) {
    return 0L;
  }
  // Attempt to minimise allocations, since SpanId#getBytes currently creates a defensive copy:
  spanId.copyBytesTo(spanIdBuffer, 0);
  return Longs.fromByteArray(spanIdBuffer);
}
 
Example #30
Source File: StatsTestUtils.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a MockableSpan with a random trace ID and span ID.
 */
@SuppressWarnings("deprecation")
public static MockableSpan generateRandomSpan(Random random) {
  return new MockableSpan(
      SpanContext.create(
          TraceId.generateRandomId(random),
          SpanId.generateRandomId(random),
          TraceOptions.DEFAULT),
      null);
}