如何在不同的日志文件中记录多个线程? [英] How to log multiple threads in different log files?
问题描述
我有一个JAVA类,它启动具有唯一ID的各种线程。
每个线程都应该登录一个以ID.log命名的唯一日志文件。
I have a JAVA class that starts various threads that have unique IDs. Each thread should log into a unique log file, named after the ID.log.
因为我只在运行时获得唯一ID,所以我必须配置Log4J以编程方式:
Because I only get the unique ID at runtime, I have to configure Log4J programatically:
// Get the jobID
myJobID = aJobID;
// Initialize the logger
myLogger = Logger.getLogger(myJobID);
FileAppender myFileAppender;
try
{
myFileAppender = new FileAppender(new SimpleLayout(), myJobID + ".log", false);
BasicConfigurator.resetConfiguration();
BasicConfigurator.configure(myFileAppender);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
现在按顺序启动作业可以正常工作 - 但是当我启动2个线程时(同一类)同时创建两个日志,但日志混合起来:第二个线程记录到第一个和第二个日志。
Now this works fine if I start jobs sequentially - but when I start 2 threads (of the same class) simultaneously, both logs are created but the logs are mixed up: The second thread logs into the first as well as the second log.
怎么可能我确保每个实例都是唯一的?
我已经尝试为每个记录器实例提供一个唯一的名称,但它没有改变任何东西。
How could I make sure that each instance is unique ? I already tried to give a unique name to each logger instance, but it did not change anything.
推荐答案
Logback有一个特殊的appender称为 SiftingAppender ,为问题类型提供了一个非常好的解决方案你形容。 SiftingAppender可用于根据任何运行时属性(包括线程ID)分离(或筛选)日志记录。
Logback has a special appender called SiftingAppender which provides a very nice solution to the type of problems you describe. A SiftingAppender can be used to separate (or sift) logging according to any runtime attribute, including thread id.
这篇关于如何在不同的日志文件中记录多个线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!