Log4j 2 根记录器覆盖一切?

Dan*_*zer 6 java logging log4j log4j2

我对 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>
Run Code Online (Sandbox Code Playgroud)

如果我通过静态记录器在这两个类 ConsoleMain 和 ClientMain 中记录一些东西

    static Logger _logger = LogManager.getLogger(ClientMain.class.getName());
Run Code Online (Sandbox Code Playgroud)

    static Logger _logger = LogManager.getLogger(ConsoleMain.class.getName());
Run Code Online (Sandbox Code Playgroud)

他们总是使用根记录器的附加程序和级别。如果根记录器的级别为上述“错误”,则它永远不会显示任何调试级别的日志输出,即使各个记录器的级别为调试。此外,它始终附加到根记录器中指定的日志文件,而不是类记录器中指定的日志文件。

因此,似乎根记录器以某种方式覆盖了所有内容。如何让 log4j 实际使用 appender 和类的记录器级别?

我尝试删除根的附加程序,但它没有记录任何内容。

谢谢!

Rem*_*pma 1

我尝试了您的设置,但无法重现该问题。这是我使用的代码:

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");
    }
}
Run Code Online (Sandbox Code Playgroud)

当我使用您的确切配置文件运行它们时,我得到以下输出:

基准.log:

07:59:51.070 [main] DEBUG com.messaging.main.ClientMain - debug from ClientMain
Run Code Online (Sandbox Code Playgroud)

调试日志:

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
Run Code Online (Sandbox Code Playgroud)

这是预期的行为。重复条目是正常的,因为默认情况下,log4j 中的可加性为 true,因此根记录器和命名记录器都将记录相同的消息(请参阅http://logging.apache.org/log4j/2.x/manual/configuration)。 html#Additivity)。我没有看到您报告的问题,即当根级别为“错误”时,调试级别消息永远不会出现在日志文件中。

也许还有其他事情正在发生。您使用的是哪个版本的 log4j2(最新版本是 beta9)?您还可以尝试使用上面的最低限度示例代码重现该问题,看看问题是否仍然存在?