Skip to content

Commit

Permalink
Implement MDC auto-instrumentation for log4j2
Browse files Browse the repository at this point in the history
  • Loading branch information
Mateusz Rzeszutek committed Sep 17, 2020
1 parent d2ce072 commit 049850e
Showing 1 changed file with 11 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@

package io.opentelemetry.instrumentation.auto.log4j.v1_2;

import static io.opentelemetry.instrumentation.api.log.LoggingContextConstants.SAMPLED;
import static io.opentelemetry.instrumentation.api.log.LoggingContextConstants.SPAN_ID;
import static io.opentelemetry.instrumentation.api.log.LoggingContextConstants.TRACE_ID;
import static java.util.Collections.singletonMap;
import static net.bytebuddy.matcher.ElementMatchers.isMethod;
import static net.bytebuddy.matcher.ElementMatchers.isPublic;
Expand Down Expand Up @@ -79,7 +82,7 @@ public static void onExit(
@Advice.This LoggingEvent event,
@Advice.Argument(0) String key,
@Advice.Return(readOnly = false) Object value) {
if ("traceId".equals(key) || "spanId".equals(key) || "sampled".equals(key)) {
if (TRACE_ID.equals(key) || SPAN_ID.equals(key) || SAMPLED.equals(key)) {
if (value != null) {
// Assume already instrumented event if traceId/spanId/sampled is present.
return;
Expand All @@ -92,13 +95,13 @@ public static void onExit(

SpanContext spanContext = span.getContext();
switch (key) {
case "traceId":
case TRACE_ID:
value = spanContext.getTraceIdAsHexString();
break;
case "spanId":
case SPAN_ID:
value = spanContext.getSpanIdAsHexString();
break;
case "sampled":
case SAMPLED:
if (spanContext.isSampled()) {
value = "true";
}
Expand Down Expand Up @@ -128,14 +131,14 @@ public static void onEnter(
}

// Assume already instrumented event if traceId is present.
if (!mdc.contains("traceId")) {
if (!mdc.contains(TRACE_ID)) {
Span span = InstrumentationContext.get(LoggingEvent.class, Span.class).get(event);
if (span != null && span.getContext().isValid()) {
SpanContext spanContext = span.getContext();
mdc.put("traceId", spanContext.getTraceIdAsHexString());
mdc.put("spanId", spanContext.getSpanIdAsHexString());
mdc.put(TRACE_ID, spanContext.getTraceIdAsHexString());
mdc.put(SPAN_ID, spanContext.getSpanIdAsHexString());
if (spanContext.isSampled()) {
mdc.put("sampled", "true");
mdc.put(SAMPLED, "true");
}
}
}
Expand Down

0 comments on commit 049850e

Please sign in to comment.