1.11.2. 使用 MDC 添加上下文日志信息


Quarkus 会覆盖日志记录映射的 diagnostics Context (MDC),以改进与其被动内核的兼容性。

1.11.2.1. 添加和读取 MDC 数据

要在 MDC 中添加数据,并将其提取到日志输出中:

  1. 使用 MDC 类设置数据。

    1. 添加 导入 org.jboss.logmanager.MDC;
    2. 设置 MDC.put (…​),如下例所示:

      JBoss Logging 和 io.quarkus.logging.Log的示例

      package me.sample;
      
      import io.quarkus.logging.Log;
      import jakarta.ws.rs.GET;
      import jakarta.ws.rs.Path;
      import org.jboss.logmanager.MDC;
      
      import java.util.UUID;
      
      @Path("/hello/jboss")
      public class GreetingResourceJbossLogging {
      
          @GET
          @Path("/test")
          public String greeting() {
              MDC.put("request.id", UUID.randomUUID().toString());
              MDC.put("request.path", "/hello/test");
              Log.info("request received");
              return "hello world!";
          }
      }

  2. 将日志格式配置为使用 %X{mdc-key}

    quarkus.log.console.format=%d{HH:mm:ss} %-5p request.id=%X{request.id} request.path=%X{request.path} [%c{2.}] (%t) %s%n

    生成的消息包含 MDC 数据:

    08:48:13 INFO request.id=c37a3a36-b7f6-4492-83a1-de41dbc26fe2 request.path=/hello/test [me.sa.GreetingResourceJbossLogging] (executor-thread-1) request received
Red Hat logoGithubredditYoutubeTwitter

学习

尝试、购买和销售

社区

關於紅帽

我们提供强化的解决方案,使企业能够更轻松地跨平台和环境(从核心数据中心到网络边缘)工作。

让开源更具包容性

红帽致力于替换我们的代码、文档和 Web 属性中存在问题的语言。欲了解更多详情,请参阅红帽博客.

关于红帽文档

Legal Notice

Theme

© 2026 Red Hat
返回顶部