你好 StackOverflow 社区,
我正在编写一个多线程应用程序,其中我需要使用 log4j 为每个线程输出一个日志文件。理想情况下,我希望为每个线程运行一个单独的日志实例。我正在讨论我应该如何解决这个问题。因为每个日志实例的文件输出位置不同,所以我需要更新log4j.appender.BrokerFile.File=
每个实例的属性。截至目前,我正在尝试创建一个新的 Logger,将新属性设置为属性对象,然后使用将新属性加载到我新创建的 Logger 对象中PropertyConfigurator.configure(log4jProperties);
虽然创建新的 Logger 实例很好,但新属性不会似乎被新实例所识别。我需要为每个新的 Logger 实例创建一个新的 FileAppender 吗?
public class Broker implements Runnable{
private Settings ss; //The Settings object associated with this broker.
private String loggerName = null;
private Logger log = null;
private Properties log4jProperties = new Properties();
}
//Constructor
public Broker(Settings ss){
this.ss = ss;
}
public void run() {
loggerName = ss.getBrokerName() + "_Logger";
log = Logger.getLogger(loggerName);
log4jProperties.setProperty("log4j.loggerName", "DEBUG, FILE");
log4jProperties.setProperty("log4j.appender.FILE","org.apache.log4j.FileAppender");
log4jProperties.setProperty("log4j.appender.FILE.File", "C:/Logz/"+loggerName+".out");
log4jProperties.setProperty("log4j.appender.FILE.ImmediateFlush", "true");
log4jProperties.setProperty("log4j.appender.FILE.Threshold", "DEBUG");
log4jProperties.setProperty("log4j.appender.FILE.Append", "FALSE");
log4jProperties.setProperty("log4j.appender.FILE.layout", "org.apache.log4j.PatternLayout");
log4jProperties.setProperty("log4j.appender.FILE.layout.conversionPattern", "%m%n");
PropertyConfigurator.configure(log4jProperties);
log.debug("This is a debug message");
// This will be set to true as long as the Broker is running
while(isRunnable){
//Listen for and process files
}
}
这是控制台输出。如您所见,正在创建新的记录器实例,但未识别新属性。
log4j:WARN No appenders could be found for logger (Broker1_Logger).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
log4j:WARN No appenders could be found for logger (Broker2_Logger).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
log4j:WARN No appenders could be found for logger (Broker3_Logger).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
这适用于每个经纪人。有没有办法直接将我的配置设置应用到 Logger 对象?例如,类似 log .PropertyConfigurator.configure(log4jproperties); 必须有一种方法可以将配置设置应用于创建的每个记录器对象。
谢谢你,
吉姆