我在java程序中使用了log4j。我用它初始化了它:

BasicConfigurator.configure(); // logger configuration
try {
     logger.setLevel(Level.DEBUG);
} catch (Exception e) {
     System.out.println("Logfile not found");
}

但是,在执行程序期间,我得到3个日志语句而不是1个。例如,

3 lines 
1047 [main] INFO ibis.Preproc.Ratings  - Added AS TIMEZONE to tZones[0] = GMT-12:00
1047 [main] INFO ibis.Preproc.Ratings  - Added AS TIMEZONE to tZones[0] = GMT-12:00
1047 [main] INFO ibis.Preproc.Ratings  - Added AS TIMEZONE to tZones[0] = GMT-12:00

而不是一行

1047 [main] INFO ibis.Preproc.Ratings  - Added AS TIMEZONE to tZones[0] = GMT-12:00

是否有任何额外的配置要对log4j进行以避免这种情况?

有帮助吗?

解决方案

我遇到过类似的行为,结果发现Log4J配置了不止一次;使用BasicConfigurator,还有我忘记的log4j.xml文件。可能是在类路径的某处有一个额外的Log4J配置吗?

其他提示

很可能你有多个Appender。请参阅log4j 手册(章节:附加组件和布局):

  

给定记录器的每个已启用的日志记录请求都将转发到该记录器中的所有appender以及层次结构中较高的appender。

您可以尝试将additivity标志设置为false。

好吧,你还没有展示你的程序是如何执行的。这是一个完整的程序,只显示一行:

import org.apache.log4j.*;

public class Test
{
    public static void main(String[] args)
    {
        BasicConfigurator.configure(); // logger configuration
        Logger logger = Logger.getLogger(Test.class);
        logger.setLevel(Level.DEBUG);
        logger.info("Hello");
    }
}

你的代码有可能真的运行了三次吗?

就我而言,每次调用BasicConfigurator.configure()时,我都会添加一个新的appender。

我解决了重置配置的问题:

BasicConfigurator.resetConfiguration() //reset first
BasicConfigurator.configure() // then configure

我必须承认我并不清楚地知道发生了什么,但它确实解决了我的问题。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top