log4j2.properties 无法配置导入包使用的 slf4j 记录器



我在文件中创建rootLogger时遇到一些问题log4j2.properties

正如您从下面的log4j2.properties文件中所看到的,我已经用infolevel定义了rootLogger,并将其指向rolling追加器RollingFile

但是,当我运行该程序时,只有从我的包生成的日志才会转到滚动文件追加器,并指定正确的日志级别,在这种情况下info

但是从我导入的打包(例如,org.apache.kafka.clients.consumer.KafkaConsumer)生成的日志不会写入滚动文件中。相反,它打印在控制台上,并且不具有指定的级别info,因为甚至打印出DEBUG日志。看起来我指定的rootLogger从未创建且有效。

在某种程度上,为什么rootLogger不工作?;换句话说,我如何控制从导入的包中生成的日志?

顺便说一句,我以这种方式使用log4j2.properties

java -Dlog4j.configurationFile=/path/to/my/log4j2.properties [options] xxx

log4j2.properties:

status = info
name = PropertiesConfig
property.directory = logs
property.filename = kafka.log
appenders = console, rolling
appender.console.type = Console
appender.console.name = STDOUT
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = [%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n
appender.rolling.type = RollingFile
appender.rolling.name = RollingFile
appender.rolling.fileName = ${directory}${sys:file.separator}${filename}
appender.rolling.filePattern = ${directory}${sys:file.separator}kafka-%d{yyyy-MM-dd-HH-mm-ss}-%i.log.gz
appender.rolling.layout.type = PatternLayout
appender.rolling.layout.pattern = [%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n
appender.rolling.policies.type = Policies
#appender.rolling.policies.time.type = TimeBasedTriggeringPolicy
#appender.rolling.policies.time.interval = 2
#appender.rolling.policies.time.modulate = true
appender.rolling.policies.size.type = SizeBasedTriggeringPolicy
appender.rolling.policies.size.size = 50MB
loggers = rolling
logger.rolling.name = kafka
logger.rolling.level = info
logger.rolling.additivity = false
logger.rolling.appenderRefs = rolling
logger.rolling.appenderRef.rolling.ref = RollingFile
rootLogger.level = info
rootLogger.additivity = false
rootLogger.appenderRefs = rolling
rootLogger.appenderRef.rolling.ref = RollingFile

更新 1

我发现了问题,但正在寻找解决方案。

问题是:我正在使用org.apache.logging.log4j.Logger但我导入的软件包使用的是org.slf4j.Logger。这就是为什么我的log4f2.properties无法从导入的软件包(例如,kafka客户端)控制记录器的原因。

然后,我的问题是:我该如何解决这个问题?

更新 2

我试图通过将log4j-slf4j-impl导入到我的项目中pom.xml.它不起作用。

更新 3

导入log4j-slf4j-impl后,我看到这个:

SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:xxx1]
SLF4J: Found binding in [jar:file:xxx2]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.

然后,我回顾所有依赖项及其依赖项,发现其中一个依赖于logback,并且此 logback 包含它记录器绑定器,这与log4j-slf4j-impl中的绑定程序复杂化。

所以我在pom的这个依赖项中添加了以下内容:

<dependencies>
<dependency>
<groupId>aaa</groupId>
<artifactId>bbb</artifactId>
<version>2.0.0</version>
<exclusions>
<exclusion>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
</exclusion>
<exclusion>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
</exclusion>
</exclusions>
</dependency>
...
</dependencies>

繁荣!问题解决了!slf4j 的记录器正在使用我给出的log4j2.properties

我自己解决了这个问题。请参阅问题部分中的更新 1、2、3。

最新更新