【问题标题】:log4j.xml ignores MDC keyslog4j.xml 忽略 MDC 键
【发布时间】:2019-08-28 09:19:00
【问题描述】:

我有一个具有以下依赖项的 Spring Boot 项目:

[INFO] +- org.springframework.boot:spring-boot-starter-log4j:jar:1.3.8.RELEASE:compile
[INFO] |  +- org.slf4j:jcl-over-slf4j:jar:1.7.25:compile
[INFO] |  +- org.slf4j:jul-to-slf4j:jar:1.7.25:compile
[INFO] |  +- org.slf4j:slf4j-log4j12:jar:1.7.25:compile
[INFO] |  \- log4j:log4j:jar:1.2.17:compile

以及MDC的用法:

import org.slf4j.MDC;

MDC.put("sheker", "kazav");
MDC.put("correlationId", "nonsense");

org.apache.log4j.Logger.getLogger(DEFAULT).info("the logger string");

log4j.xml 中,我正在尝试打印映射的诊断上下文键,如下所示:

<appender name="console" class="com.sheker.CustomConsoleAppender">
    <param name="Target" value="System.out" />
    <layout class="org.apache.log4j.PatternLayout">
        <param name="ConversionPattern" value="[%X{correlationId}] [%X{sheker}] - %m" />
    </layout>
</appender>

我希望得到:

[nonsense] [kazav] - the logger string

但实际输出是:

[] [] - the logger string

为什么 MDC 密钥会被忽略?

【问题讨论】:

    标签: spring-boot log4j log4j2 mdc


    【解决方案1】:

    如果您的类路径包含多个 SLF4J 绑定。那么您可以排除其他人并仅保留一个绑定。在 springboot 中,其他依赖的 jar 可以将 slf4j 或其他日志框架添加到您的项目中。在 maven 命令下运行以查找哪个 jar 带来了这些绑定,然后将它们从 pom 中排除

    mvn dependency:tree -Dincludes=:slf4j*
    

    要从另一个依赖项中排除 jar,请将其添加到依赖项中

    <exclusions>
            <exclusion>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-simple</artifactId>
            </exclusion>
        </exclusions>
    

    【讨论】:

      【解决方案2】:

      问题是:

      SLF4J: Class path contains multiple SLF4J bindings.
      SLF4J: Found binding in [jar:file:/path/repository/ch/qos/logback/logback-classic/1.1.11/logback-classic-1.1.11.jar!/org/slf4j/impl/StaticLoggerBinder.class]
      SLF4J: Found binding in [jar:file:/path/repository/org/slf4j/slf4j-log4j12/1.7.25/slf4j-log4j12-1.7.25.jar!/org/slf4j/impl/StaticLoggerBinder.class]
      SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
      SLF4J: Actual binding is of type [ch.qos.logback.classic.util.ContextSelectorStaticBinder]
      

      解决办法是:

      <dependency>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-starter-data-jpa</artifactId>
              <exclusions>
                  <exclusion>
                      <groupId>org.slf4j</groupId>
                      <artifactId>log4j-over-slf4j</artifactId>
                  </exclusion>
                  <exclusion>
                      <groupId>org.springframework.boot</groupId>
                      <artifactId>spring-boot-starter-logging</artifactId>
                  </exclusion>
              </exclusions>
          </dependency>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-12-27
        • 2016-11-16
        • 1970-01-01
        • 2022-11-24
        • 2011-04-24
        • 2021-08-11
        • 2012-09-04
        相关资源
        最近更新 更多