After accessing APM through Tencent Cloud OpenTelemetry enhanced Java probe, it is easy to output context TraceID and SpanID in application logs. Only modifying the pattern in the log configuration file can realize the injection of TraceID and SpanID. The log injection feature of OpenTelemetry enhanced Java probe supports the following logging frameworks:
Log4j 1.2+
Log4j2 2.7+
Logback 1.0+
In the log configuration file, TraceID and SpanID are injected using %X{trace_id}
and %X{span_id}
fields respectively. If there is no TraceID or SpanID in the context, it will not affect the output of the entire line of logs.
Log4j
Example of modifying log4j.properties file:
log4j.appender.warn.layout=org.apache.log4j.PatternLayout
log4j.appender.warn.layout.ConversionPattern=traceId: %X{trace_id} spanId: %X{span_id} - %m%n
Log4j2
Log4j2 supports multiple format configuration files, including XML, JSON, YAML, Properties, etc. Taking XML format as an example, there are multiple ways to write Pattern. Please refer to one of the existing ways:
<PatternLayout pattern="traceId: %X{trace_id} spanId: %X{span_id} - %m%n"/>
<PatternLayout>
<Pattern>traceId: %X{trace_id} spanId: %X{span_id} - %m%n</Pattern>
</PatternLayout>
<Layout type="PatternLayout" pattern="traceId: %X{trace_id} spanId: %X{span_id} - %m%n"/>
Logback
Example of modifying logback.xml file:
<encoder>
<pattern>traceId: %X{trace_id} spanId: %X{span_id} %msg%n</pattern>
</encoder>
Output Effect
When TraceID and SpanID exist in the context:
When TraceID and SpanID do not exist in the context: