英文:
Logging opentelemetry tracid in spring boot reactive server
问题
我正在开发一个基于Spring Boot 3的Java REST API服务器,使用spring-boot-starter-webflux。
如何集成Opentelemetry TraceID,以便每个日志行都包含TraceID?
谢谢,
英文:
I am developing a java rest api server with spring boot 3 based on spring-boot-starter-webflux.
How to integrate opentelemetry traceid so that each log line contains the traceid?
Thanks,
答案1
得分: 1
答案取决于您选择的仪器。
如果您正在使用 java agent,则无需包含任何依赖项,您可以直接使用 thread_id
和 span_id
来配置您的记录器,就像在此 log4j 示例中一样:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout
pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} trace_id=%X{trace_id} span_id=%X{span_id} trace_flags=%X{trace_flags} - %msg%n"/>
</Console>
</Appenders>
<Loggers>
<Root>
<AppenderRef ref="Console" level="All"/>
</Root>
</Loggers>
</Configuration>
如果您没有使用 java agent,您需要包含一个库,将跨度和跟踪ID注入上下文或MDC对象中。
除此之外,它与上面的示例一样工作。
- 对于log4j,请使用 opentelemetry-log4j-context-data-2.17-autoconfigure
- 对于logback,请使用 opentelemetry-logback-mdc-1.0
请注意,还可以使用OTLP协议将日志发送到OpenTelemetry后端。从技术上讲,这意味着添加一个与控制台附加程序独立的不同附加程序。此附加程序将跨度和跟踪ID与消息正文分开传输(作为属性)。
- 如果您正在使用java代理,此附加程序将自动为您添加。
- 如果您没有使用java代理,您可以在grafana OpenTelemetry starter中找到一个完整的示例(完全披露:我是这个starter的作者)。
英文:
The answer depends on your choice of instrumentation.
If you're using the java agent, you don't need to include any dependencies, you can use thread_id
and span_id
directly to configure your logger, such as in this log4j example:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout
pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} trace_id=%X{trace_id} span_id=%X{span_id} trace_flags=%X{trace_flags} - %msg%n"/>
</Console>
</Appenders>
<Loggers>
<Root>
<AppenderRef ref="Console" level="All"/>
</Root>
</Loggers>
</Configuration>
If you're not using the java agent, you need to include a library that injects the span and trace ID into the context or MDC object.
Other than that, it works as in the example above.
- For log4j, use opentelemetry-log4j-context-data-2.17-autoconfigure
- For logback, use opentelemetry-logback-mdc-1.0
Note that it's also possible to send logs to an OpenTelemetry backend using the OTLP protocol. Technically this means adding a different appender independent from the console appender. This appender will transmit the span and trace ID separately from the message body (as attributes).
- If you're using the java agent, this appender is automatically added for you.
- If you're not using the java agent, you can find a full example in the grafana OpenTelemetry starter (full disclosure: I'm the author of this starter).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论