diff --git a/log4j-layout-template-json-test/src/test/java/org/apache/logging/log4j/layout/template/json/GcpLayoutTest.java b/log4j-layout-template-json-test/src/test/java/org/apache/logging/log4j/layout/template/json/GcpLayoutTest.java index a61a764cd13..c257b1c8af8 100644 --- a/log4j-layout-template-json-test/src/test/java/org/apache/logging/log4j/layout/template/json/GcpLayoutTest.java +++ b/log4j-layout-template-json-test/src/test/java/org/apache/logging/log4j/layout/template/json/GcpLayoutTest.java @@ -28,6 +28,9 @@ import java.util.Locale; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.core.LogEvent; +import org.apache.logging.log4j.core.impl.ContextDataFactory; +import org.apache.logging.log4j.core.impl.Log4jLogEvent; +import org.apache.logging.log4j.util.StringMap; import org.junit.jupiter.api.Test; class GcpLayoutTest { @@ -54,6 +57,29 @@ void test_full_log_events() { LogEventFixture.createFullLogEvents(LOG_EVENT_COUNT).forEach(GcpLayoutTest::verifySerialization); } + @Test + void test_trace_context() { + final StringMap contextData = ContextDataFactory.createContextData(); + contextData.putValue("trace_id", "4bf92f3577b34da6a3ce929d0e0e4736"); + contextData.putValue("span_id", "00f067aa0ba902b7"); + + LogEvent logEvent = + Log4jLogEvent.newBuilder().setContextData(contextData).build(); + + usingSerializedLogEventAccessor(LAYOUT, logEvent, accessor -> { + // Verify trace id + assertThat(accessor.getString("logging.googleapis.com/trace")) + .isEqualTo("4bf92f3577b34da6a3ce929d0e0e4736"); + + // Verify span ID + assertThat(accessor.getString("logging.googleapis.com/spanId")).isEqualTo("00f067aa0ba902b7"); + + // Verify trace sampled + assertThat(accessor.getBoolean("logging.googleapis.com/trace_sampled")) + .isTrue(); + }); + } + private static void verifySerialization(final LogEvent logEvent) { usingSerializedLogEventAccessor(LAYOUT, logEvent, accessor -> { diff --git a/log4j-layout-template-json/src/main/resources/GcpLayout.json b/log4j-layout-template-json/src/main/resources/GcpLayout.json index 563e5a2fc3c..f00c84d981e 100644 --- a/log4j-layout-template-json/src/main/resources/GcpLayout.json +++ b/log4j-layout-template-json/src/main/resources/GcpLayout.json @@ -40,6 +40,15 @@ "$resolver": "counter", "stringified": true }, + "logging.googleapis.com/trace": { + "$resolver": "mdc", + "key": "trace_id" + }, + "logging.googleapis.com/spanId": { + "$resolver": "mdc", + "key": "span_id" + }, + "logging.googleapis.com/trace_sampled": true, "_exception": { "class": { "$resolver": "exception", diff --git a/src/changelog/.2.x.x/add_GcpLayout_tracing_support.xml b/src/changelog/.2.x.x/add_GcpLayout_tracing_support.xml new file mode 100644 index 00000000000..f37e80fdbcd --- /dev/null +++ b/src/changelog/.2.x.x/add_GcpLayout_tracing_support.xml @@ -0,0 +1,8 @@ + + + + Add trace context fields to `GcpLayout.json` +