Search in sources :

Example 16 with SpanContext

use of io.opencensus.trace.SpanContext in project instrumentation-java by census-instrumentation.

the class TracezZPageHandler method emitSingleSpan.

// Emits the internal html for a single {@link SpanData}.
@SuppressWarnings("deprecation")
private static void emitSingleSpan(Formatter formatter, SpanData span) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(TimeUnit.SECONDS.toMillis(span.getStartTimestamp().getSeconds()));
    long microsField = TimeUnit.NANOSECONDS.toMicros(span.getStartTimestamp().getNanos());
    String elapsedSecondsStr = span.getEndTimestamp() != null ? String.format("%13.6f", durationToNanos(span.getEndTimestamp().subtractTimestamp(span.getStartTimestamp())) * 1.0e-9) : String.format("%13s", " ");
    SpanContext spanContext = span.getContext();
    formatter.format("<b>%04d/%02d/%02d-%02d:%02d:%02d.%06d %s     TraceId: <b style=\"color:%s;\">%s</b> " + "SpanId: %s ParentSpanId: %s</b>%n", calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DAY_OF_MONTH), calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), calendar.get(Calendar.SECOND), microsField, elapsedSecondsStr, spanContext.getTraceOptions().isSampled() ? SAMPLED_TRACE_ID_COLOR : NOT_SAMPLED_TRACE_ID_COLOR, BaseEncoding.base16().lowerCase().encode(spanContext.getTraceId().getBytes()), BaseEncoding.base16().lowerCase().encode(spanContext.getSpanId().getBytes()), BaseEncoding.base16().lowerCase().encode(span.getParentSpanId() == null ? SpanId.INVALID.getBytes() : span.getParentSpanId().getBytes()));
    int lastEntryDayOfYear = calendar.get(Calendar.DAY_OF_YEAR);
    Timestamp lastTimestampNanos = span.getStartTimestamp();
    TimedEvents<Annotation> annotations = span.getAnnotations();
    TimedEvents<io.opencensus.trace.NetworkEvent> networkEvents = span.getNetworkEvents();
    List<TimedEvent<?>> timedEvents = new ArrayList<TimedEvent<?>>(annotations.getEvents());
    timedEvents.addAll(networkEvents.getEvents());
    Collections.sort(timedEvents, new TimedEventComparator());
    for (TimedEvent<?> event : timedEvents) {
        // Special printing so that durations smaller than one second
        // are left padded with blanks instead of '0' characters.
        // E.g.,
        // Number                  Printout
        // ---------------------------------
        // 0.000534                  .   534
        // 1.000534                 1.000534
        long deltaMicros = TimeUnit.NANOSECONDS.toMicros(durationToNanos(event.getTimestamp().subtractTimestamp(lastTimestampNanos)));
        String deltaString;
        if (deltaMicros >= 1000000) {
            deltaString = String.format("%.6f", (deltaMicros / 1000000.0));
        } else {
            deltaString = String.format(".%6d", deltaMicros);
        }
        calendar.setTimeInMillis(TimeUnit.SECONDS.toMillis(event.getTimestamp().getSeconds()) + TimeUnit.NANOSECONDS.toMillis(event.getTimestamp().getNanos()));
        microsField = TimeUnit.NANOSECONDS.toMicros(event.getTimestamp().getNanos());
        int dayOfYear = calendar.get(Calendar.DAY_OF_YEAR);
        if (dayOfYear == lastEntryDayOfYear) {
            formatter.format("%11s", "");
        } else {
            formatter.format("%04d/%02d/%02d-", calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DAY_OF_MONTH));
            lastEntryDayOfYear = dayOfYear;
        }
        formatter.format("%02d:%02d:%02d.%06d %13s ... %s%n", calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), calendar.get(Calendar.SECOND), microsField, deltaString, htmlEscaper().escape(event.getEvent() instanceof Annotation ? renderAnnotation((Annotation) event.getEvent()) : renderNetworkEvents((io.opencensus.trace.NetworkEvent) castNonNull(event.getEvent()))));
        lastTimestampNanos = event.getTimestamp();
    }
    Status status = span.getStatus();
    if (status != null) {
        formatter.format("%44s %s%n", "", htmlEscaper().escape(renderStatus(status)));
    }
    formatter.format("%44s %s%n", "", htmlEscaper().escape(renderAttributes(span.getAttributes().getAttributeMap())));
}
Also used : Status(io.opencensus.trace.Status) SpanContext(io.opencensus.trace.SpanContext) Calendar(java.util.Calendar) ArrayList(java.util.ArrayList) TimedEvent(io.opencensus.trace.export.SpanData.TimedEvent) Timestamp(io.opencensus.common.Timestamp) Annotation(io.opencensus.trace.Annotation)

Example 17 with SpanContext

use of io.opencensus.trace.SpanContext in project instrumentation-java by census-instrumentation.

the class ContextDataUtils method getContextAndTracingData.

static StringMap getContextAndTracingData() {
    SpanContext spanContext = getCurrentSpanContext();
    ReadOnlyThreadContextMap context = ThreadContext.getThreadContextMap();
    SortedArrayStringMap stringMap;
    if (context == null) {
        stringMap = new SortedArrayStringMap(ThreadContext.getImmutableContext());
    } else {
        StringMap contextData = context.getReadOnlyContextData();
        stringMap = new SortedArrayStringMap(contextData.size() + 3);
        stringMap.putAll(contextData);
    }
    // TODO(sebright): Move the calls to TraceId.toLowerBase16() and SpanId.toLowerBase16() out of
    // the critical path by wrapping the trace and span IDs in objects that call toLowerBase16() in
    // their toString() methods, after there is a fix for
    // https://github.com/census-instrumentation/opencensus-java/issues/1436.
    stringMap.putValue(OpenCensusTraceContextDataInjector.TRACE_ID_CONTEXT_KEY, spanContext.getTraceId().toLowerBase16());
    stringMap.putValue(OpenCensusTraceContextDataInjector.SPAN_ID_CONTEXT_KEY, spanContext.getSpanId().toLowerBase16());
    stringMap.putValue(OpenCensusTraceContextDataInjector.TRACE_SAMPLED_CONTEXT_KEY, spanContext.getTraceOptions().isSampled() ? "true" : "false");
    return stringMap;
}
Also used : SortedArrayStringMap(org.apache.logging.log4j.util.SortedArrayStringMap) StringMap(org.apache.logging.log4j.util.StringMap) SpanContext(io.opencensus.trace.SpanContext) SortedArrayStringMap(org.apache.logging.log4j.util.SortedArrayStringMap) ReadOnlyThreadContextMap(org.apache.logging.log4j.spi.ReadOnlyThreadContextMap)

Example 18 with SpanContext

use of io.opencensus.trace.SpanContext in project instrumentation-java by census-instrumentation.

the class InstanaExporterHandler method convertToJson.

static String convertToJson(Collection<SpanData> spanDataList) {
    StringBuilder sb = new StringBuilder();
    sb.append('[');
    for (final SpanData span : spanDataList) {
        final SpanContext spanContext = span.getContext();
        final SpanId parentSpanId = span.getParentSpanId();
        final Timestamp startTimestamp = span.getStartTimestamp();
        final Timestamp endTimestamp = span.getEndTimestamp();
        final Status status = span.getStatus();
        if (status == null || endTimestamp == null) {
            continue;
        }
        if (sb.length() > 1) {
            sb.append(',');
        }
        sb.append('{');
        sb.append("\"spanId\":\"").append(encodeSpanId(spanContext.getSpanId())).append("\",");
        sb.append("\"traceId\":\"").append(encodeTraceId(spanContext.getTraceId())).append("\",");
        if (parentSpanId != null) {
            sb.append("\"parentId\":\"").append(encodeSpanId(parentSpanId)).append("\",");
        }
        sb.append("\"timestamp\":").append(toMillis(startTimestamp)).append(',');
        sb.append("\"duration\":").append(toMillis(startTimestamp, endTimestamp)).append(',');
        sb.append("\"name\":\"").append(toSpanName(span)).append("\",");
        sb.append("\"type\":\"").append(toSpanType(span)).append('"');
        if (!status.isOk()) {
            sb.append(",\"error\":").append("true");
        }
        Map<String, AttributeValue> attributeMap = span.getAttributes().getAttributeMap();
        if (attributeMap.size() > 0) {
            StringBuilder dataSb = new StringBuilder();
            dataSb.append('{');
            for (Entry<String, AttributeValue> entry : attributeMap.entrySet()) {
                if (dataSb.length() > 1) {
                    dataSb.append(',');
                }
                dataSb.append("\"").append(entry.getKey()).append("\":\"").append(attributeValueToString(entry.getValue())).append("\"");
            }
            dataSb.append('}');
            sb.append(",\"data\":").append(dataSb);
        }
        sb.append('}');
    }
    sb.append(']');
    return sb.toString();
}
Also used : Status(io.opencensus.trace.Status) AttributeValue(io.opencensus.trace.AttributeValue) SpanContext(io.opencensus.trace.SpanContext) SpanData(io.opencensus.trace.export.SpanData) Timestamp(io.opencensus.common.Timestamp) SpanId(io.opencensus.trace.SpanId)

Example 19 with SpanContext

use of io.opencensus.trace.SpanContext in project instrumentation-java by census-instrumentation.

the class ZipkinExporterHandler method generateSpan.

@SuppressWarnings("deprecation")
static Span generateSpan(SpanData spanData, Endpoint localEndpoint) {
    SpanContext context = spanData.getContext();
    long startTimestamp = toEpochMicros(spanData.getStartTimestamp());
    // TODO(sebright): Fix the Checker Framework warning.
    @SuppressWarnings("nullness") long endTimestamp = toEpochMicros(spanData.getEndTimestamp());
    // TODO(bdrutu): Fix the Checker Framework warning.
    @SuppressWarnings("nullness") Span.Builder spanBuilder = Span.newBuilder().traceId(context.getTraceId().toLowerBase16()).id(context.getSpanId().toLowerBase16()).kind(toSpanKind(spanData)).name(spanData.getName()).timestamp(toEpochMicros(spanData.getStartTimestamp())).duration(endTimestamp - startTimestamp).localEndpoint(localEndpoint);
    if (spanData.getParentSpanId() != null && spanData.getParentSpanId().isValid()) {
        spanBuilder.parentId(spanData.getParentSpanId().toLowerBase16());
    }
    for (Map.Entry<String, AttributeValue> label : spanData.getAttributes().getAttributeMap().entrySet()) {
        spanBuilder.putTag(label.getKey(), attributeValueToString(label.getValue()));
    }
    Status status = spanData.getStatus();
    if (status != null) {
        spanBuilder.putTag(STATUS_CODE, status.getCanonicalCode().toString());
        if (status.getDescription() != null) {
            spanBuilder.putTag(STATUS_DESCRIPTION, status.getDescription());
        }
        if (!status.isOk()) {
            spanBuilder.putTag(STATUS_ERROR, status.getCanonicalCode().toString());
        }
    }
    for (TimedEvent<Annotation> annotation : spanData.getAnnotations().getEvents()) {
        spanBuilder.addAnnotation(toEpochMicros(annotation.getTimestamp()), annotation.getEvent().getDescription());
    }
    for (TimedEvent<io.opencensus.trace.MessageEvent> messageEvent : spanData.getMessageEvents().getEvents()) {
        spanBuilder.addAnnotation(toEpochMicros(messageEvent.getTimestamp()), messageEvent.getEvent().getType().name());
    }
    return spanBuilder.build();
}
Also used : Status(io.opencensus.trace.Status) AttributeValue(io.opencensus.trace.AttributeValue) SpanContext(io.opencensus.trace.SpanContext) Span(zipkin2.Span) Annotation(io.opencensus.trace.Annotation) Map(java.util.Map)

Example 20 with SpanContext

use of io.opencensus.trace.SpanContext in project instrumentation-java by census-instrumentation.

the class OpenCensusTraceContextDataInjectorTest method rawContextDataWithTracingData.

@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();
    }
}
Also used : SpanContext(io.opencensus.trace.SpanContext) Scope(io.opencensus.common.Scope) Test(org.junit.Test)

Aggregations

SpanContext (io.opencensus.trace.SpanContext)21 Test (org.junit.Test)8 Timestamp (io.opencensus.common.Timestamp)6 AttributeValue (io.opencensus.trace.AttributeValue)4 Status (io.opencensus.trace.Status)4 SpanData (io.opencensus.trace.export.SpanData)4 Span (io.opencensus.trace.Span)3 SpanId (io.opencensus.trace.SpanId)3 ArrayList (java.util.ArrayList)3 CloudTraceContext (com.google.apphosting.api.CloudTraceContext)2 Context (io.grpc.Context)2 Annotation (io.opencensus.trace.Annotation)2 SpanBuilder (io.opencensus.trace.SpanBuilder)2 Map (java.util.Map)2 VisibleForTesting (com.google.common.annotations.VisibleForTesting)1 Span (com.google.devtools.cloudtrace.v2.Span)1 SpanName (com.google.devtools.cloudtrace.v2.SpanName)1 TruncatableString (com.google.devtools.cloudtrace.v2.TruncatableString)1 Metadata (io.grpc.Metadata)1 ServerStreamTracer (io.grpc.ServerStreamTracer)1