Java源码示例:io.opencensus.trace.TraceId

示例1
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();
}
 
示例2
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);
  }
}
 
示例3
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);
}
 
示例4
@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();
}
 
示例5
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());
}
 
示例6
/**
 * 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);
  }
}
 
示例7
@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");
}
 
示例8
@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");
}
 
示例9
@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");
}
 
示例10
@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");
}
 
示例11
@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");
}
 
示例12
@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("[]");
}
 
示例13
@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);
}
 
示例14
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"))));
}
 
示例15
@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());
}
 
示例16
/**
 * 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);
}
 
示例17
@Override
public boolean shouldSample(
    @Nullable SpanContext parentContext,
    @Nullable Boolean hasRemoteParent,
    TraceId traceId,
    SpanId spanId,
    String name,
    List<Span> parentLinks) {
  return true;
}
 
示例18
@Override
public final boolean shouldSample(
    @Nullable SpanContext parentContext,
    @Nullable Boolean hasRemoteParent,
    TraceId traceId,
    SpanId spanId,
    String name,
    @Nullable List<Span> parentLinks) {
  // If the parent is sampled keep the sampling decision.
  if (parentContext != null && parentContext.getTraceOptions().isSampled()) {
    return true;
  }
  if (parentLinks != null) {
    // If any parent link is sampled keep the sampling decision.
    for (Span parentLink : parentLinks) {
      if (parentLink.getContext().getTraceOptions().isSampled()) {
        return true;
      }
    }
  }
  // Always sample if we are within probability range. This is true even for child spans (that
  // may have had a different sampling decision made) to allow for different sampling policies,
  // and dynamic increases to sampling probabilities for debugging purposes.
  // Note use of '<' for comparison. This ensures that we never sample for probability == 0.0,
  // while allowing for a (very) small chance of *not* sampling if the id == Long.MAX_VALUE.
  // This is considered a reasonable tradeoff for the simplicity/performance requirements (this
  // code is executed in-line for every Span creation).
  return Math.abs(traceId.getLowerLong()) < getIdUpperBound();
}
 
示例19
@Override
public boolean shouldSample(
    @Nullable SpanContext parentContext,
    @Nullable Boolean hasRemoteParent,
    TraceId traceId,
    SpanId spanId,
    String name,
    List<Span> parentLinks) {
  return false;
}
 
示例20
/** Create a link. */
@Benchmark
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public Link createLink(Data data) {
  return Link.fromSpanContext(
      SpanContext.create(
          TraceId.fromBytes(new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0}),
          SpanId.fromBytes(new byte[] {1, 2, 3, 4, 5, 6, 7, 0}),
          TraceOptions.DEFAULT,
          TRACESTATE_DEFAULT),
      Link.Type.PARENT_LINKED_SPAN);
}
 
示例21
@Override
public <C /*>>> extends @NonNull Object*/> SpanContext extract(C carrier, Getter<C> getter)
    throws SpanContextParseException {
  checkNotNull(carrier, "carrier");
  checkNotNull(getter, "getter");
  try {
    TraceId traceId;
    String traceIdStr = getter.get(carrier, X_B3_TRACE_ID);
    if (traceIdStr != null) {
      if (traceIdStr.length() == TraceId.SIZE) {
        // This is an 8-byte traceID.
        traceIdStr = UPPER_TRACE_ID + traceIdStr;
      }
      traceId = TraceId.fromLowerBase16(traceIdStr);
    } else {
      throw new SpanContextParseException("Missing X_B3_TRACE_ID.");
    }
    SpanId spanId;
    String spanIdStr = getter.get(carrier, X_B3_SPAN_ID);
    if (spanIdStr != null) {
      spanId = SpanId.fromLowerBase16(spanIdStr);
    } else {
      throw new SpanContextParseException("Missing X_B3_SPAN_ID.");
    }
    TraceOptions traceOptions = TraceOptions.DEFAULT;
    if (SAMPLED_VALUE.equals(getter.get(carrier, X_B3_SAMPLED))
        || FLAGS_VALUE.equals(getter.get(carrier, X_B3_FLAGS))) {
      traceOptions = TraceOptions.builder().setIsSampled(true).build();
    }
    return SpanContext.create(traceId, spanId, traceOptions, TRACESTATE_DEFAULT);
  } catch (IllegalArgumentException e) {
    throw new SpanContextParseException("Invalid input.", e);
  }
}
 
示例22
@Override
public SpanContext fromByteArray(byte[] bytes) throws SpanContextParseException {
  checkNotNull(bytes, "bytes");
  if (bytes.length == 0 || bytes[0] != VERSION_ID) {
    throw new SpanContextParseException("Unsupported version.");
  }
  if (bytes.length < REQUIRED_FORMAT_LENGTH) {
    throw new SpanContextParseException("Invalid input: truncated");
  }
  // TODO: the following logic assumes that fields are written in ID order. The spec does not say
  // that. If it decides not to, this logic would need to be more like a loop
  TraceId traceId;
  SpanId spanId;
  TraceOptions traceOptions = TraceOptions.DEFAULT;
  int pos = 1;
  if (bytes[pos] == TRACE_ID_FIELD_ID) {
    traceId = TraceId.fromBytes(bytes, pos + ID_SIZE);
    pos += ID_SIZE + TraceId.SIZE;
  } else {
    // TODO: update the spec to suggest that the trace ID is not actually optional
    throw new SpanContextParseException("Invalid input: expected trace ID at offset " + pos);
  }
  if (bytes[pos] == SPAN_ID_FIELD_ID) {
    spanId = SpanId.fromBytes(bytes, pos + ID_SIZE);
    pos += ID_SIZE + SpanId.SIZE;
  } else {
    // TODO: update the spec to suggest that the span ID is not actually optional.
    throw new SpanContextParseException("Invalid input: expected span ID at offset " + pos);
  }
  // Check to see if we are long enough to include an options field, and also that the next field
  // is an options field. Per spec we simply stop parsing at first unknown field instead of
  // failing.
  if (bytes.length > pos && bytes[pos] == TRACE_OPTION_FIELD_ID) {
    if (bytes.length < ALL_FORMAT_LENGTH) {
      throw new SpanContextParseException("Invalid input: truncated");
    }
    traceOptions = TraceOptions.fromByte(bytes[pos + ID_SIZE]);
  }
  return SpanContext.create(traceId, spanId, traceOptions, TRACESTATE_DEFAULT);
}
 
示例23
@Setup
public void setup() {
  textFormatBase =
      new TextFormatBenchmarkBase(Tracing.getPropagationComponent().getTraceContextFormat());
  Random random = new Random(1234);
  spanContext =
      SpanContext.create(
          TraceId.generateRandomId(random),
          SpanId.generateRandomId(random),
          TraceOptions.builder().setIsSampled(random.nextBoolean()).build(),
          Tracestate.builder().build());
  spanContextHeaders = new HashMap<String, String>();
  textFormatBase.inject(spanContext, spanContextHeaders);
}
 
示例24
@Setup
public void setup() {
  textFormatBase = new TextFormatBenchmarkBase(new B3Format());
  Random random = new Random(1234);
  spanContext =
      SpanContext.create(
          TraceId.generateRandomId(random),
          SpanId.generateRandomId(random),
          TraceOptions.builder().setIsSampled(random.nextBoolean()).build(),
          Tracestate.builder().build());
  spanContextHeaders = new HashMap<String, String>();
  textFormatBase.inject(spanContext, spanContextHeaders);
}
 
示例25
@Setup
public void setup() {
  binaryFormat = new BinaryFormatImpl();
  Random random = new Random(1234);
  spanContext =
      SpanContext.create(
          TraceId.generateRandomId(random),
          SpanId.generateRandomId(random),
          TraceOptions.builder().setIsSampled(random.nextBoolean()).build(),
          Tracestate.builder().build());
  spanContextBinary = binaryFormat.toByteArray(spanContext);
}
 
示例26
@Override
public <C /*>>> extends @NonNull Object*/> SpanContext extract(C carrier, Getter<C> getter)
    throws SpanContextParseException {
  checkNotNull(carrier, "carrier");
  checkNotNull(getter, "getter");
  try {
    String headerStr = getter.get(carrier, HEADER_NAME);
    if (headerStr == null || headerStr.length() < MIN_HEADER_SIZE) {
      throw new SpanContextParseException("Missing or too short header: " + HEADER_NAME);
    }
    checkArgument(headerStr.charAt(TRACE_ID_SIZE) == SPAN_ID_DELIMITER, "Invalid TRACE_ID size");

    TraceId traceId = TraceId.fromLowerBase16(headerStr.subSequence(0, TRACE_ID_SIZE));
    int traceOptionsPos = headerStr.indexOf(TRACE_OPTION_DELIMITER, TRACE_ID_SIZE);
    CharSequence spanIdStr =
        headerStr.subSequence(
            SPAN_ID_START_POS, traceOptionsPos < 0 ? headerStr.length() : traceOptionsPos);
    SpanId spanId = longToSpanId(UnsignedLongs.parseUnsignedLong(spanIdStr.toString(), 10));
    TraceOptions traceOptions = OPTIONS_NOT_SAMPLED;
    if (traceOptionsPos > 0) {
      String traceOptionsStr = headerStr.substring(traceOptionsPos + TRACE_OPTION_DELIMITER_SIZE);
      if ((UnsignedInts.parseUnsignedInt(traceOptionsStr, 10) & CLOUD_TRACE_IS_SAMPLED) != 0) {
        traceOptions = OPTIONS_SAMPLED;
      }
    }
    return SpanContext.create(traceId, spanId, traceOptions, TRACESTATE_DEFAULT);
  } catch (IllegalArgumentException e) {
    throw new SpanContextParseException("Invalid input", e);
  }
}
 
示例27
@SuppressWarnings("deprecation")
private static SpanContext fromSleuthSpan(org.springframework.cloud.sleuth.Span span) {
  return SpanContext.create(
      TraceId.fromBytes(
          ByteBuffer.allocate(TraceId.SIZE)
              .putLong(span.getTraceIdHigh())
              .putLong(span.getTraceId())
              .array()),
      SpanId.fromBytes(ByteBuffer.allocate(SpanId.SIZE).putLong(span.getSpanId()).array()),
      Boolean.TRUE.equals(span.isExportable()) ? sampledOptions : notSampledOptions);
}
 
示例28
@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");
}
 
示例29
@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");
}
 
示例30
@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();
  }
}