我对 Log4j 2 比较陌生。目前,我有这个配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<File name="DebugFile" fileName="../../logs/debug.log">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</File>
<File name="BenchmarkFile" fileName="../../logs/benchmark.log">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</File>
</Appenders>
<Loggers>
<Logger name="com.messaging.main.ConsoleMain" level="debug">
<AppenderRef ref="DebugFile"/>
</Logger>
<Logger name="com.messaging.main.ClientMain" level="debug">
<AppenderRef ref="BenchmarkFile"/>
</Logger>
<Root level="error">
<AppenderRef ref="DebugFile"/>
</Root>
</Loggers>
</Configuration>
如果我通过静态记录器在这两个类控制台主和客户端中记录一些东西
static Logger _logger = LogManager.getLogger(ClientMain.class.getName());
和
static Logger _logger = LogManager.getLogger(ConsoleMain.class.getName());
它们始终使用根记录器的追加器和级别。如果根记录器的级别如上所述为"错误",则它永远不会显示任何调试级别日志记录输出,即使单个记录器的级别是调试。此外,它始终附加到根记录器中指定的日志文件,而不是类的记录器中指定的日志文件。
因此,根记录器似乎以某种方式覆盖了所有内容。如何让 log4j 实际使用类的追加器和记录器的级别?
我尝试删除根的附加器,但随后它没有记录任何内容。
谢谢!
我尝试了您的设置,但无法重现该问题。这是我使用的代码:
package com.messaging.main;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class ClientMain {
public static void main(String[] args) throws Exception {
Logger logger = LogManager.getLogger(ClientMain.class);
logger.debug("debug from ClientMain");
}
}
package com.messaging.main;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class ConsoleMain {
public static void main(String[] args) throws Exception {
Logger logger = LogManager.getLogger(ConsoleMain.class);
logger.debug("debug from ConsoleMain");
}
}
当我使用您的确切配置文件运行这些时,我得到以下输出:
基准.log:
07:59:51.070 [main] DEBUG com.messaging.main.ClientMain - debug from ClientMain
调试.log:
07:59:51.070 [main] DEBUG com.messaging.main.ClientMain - debug from ClientMain
07:59:58.306 [main] DEBUG com.messaging.main.ConsoleMain - debug from ConsoleMain
07:59:58.306 [main] DEBUG com.messaging.main.ConsoleMain - debug from ConsoleMain
这是预期行为。重复条目是正常的,因为默认情况下 log4j 中的可加性为 true,因此根记录器和命名记录器都将记录相同的消息(请参阅 http://logging.apache.org/log4j/2.x/manual/configuration.html#Additivity)。我没有看到您报告的问题,即当根级别为"错误"时,调试级消息永远不会出现在日志文件中。
也许还有其他事情正在发生。您使用的是哪个版本的 log4j2(最新的现在是 beta9)?您还可以尝试使用上面的最小示例代码重现问题,看看问题是否仍然存在?