gpt4 book ai didi

java - Log4j 2 根记录器覆盖一切?

转载 作者:搜寻专家 更新时间:2023-11-01 03:39:18 25 4
gpt4 key购买 nike

我是 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>

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

    static Logger _logger = LogManager.getLogger(ClientMain.class.getName());

    static Logger _logger = LogManager.getLogger(ConsoleMain.class.getName());

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

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

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

谢谢!

最佳答案

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

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");
}
}

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

基准测试日志:

07:59:51.070 [main] DEBUG com.messaging.main.ClientMain - debug from ClientMain

调试日志:

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 中默认可加性为真,因此根记录器和命名记录器将记录相同的消息(参见 http://logging.apache.org/log4j/2.x/manual/configuration.html#Additivity )。我没有看到您报告的问题,即当根级别为“错误”时,调试级别的消息从不出现在日志文件中。

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

关于java - Log4j 2 根记录器覆盖一切?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19210527/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com