log4j.xml 忽略 MDC 密钥

log4j.xml ignores MDC keys

我有一个 Spring 引导项目,它具有以下依赖项:

[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 密钥被忽略?

问题是:

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>

如果您的 class 路径包含多个 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>