如何使用一个 log4j 配置文件创建2个独立的日志文件?

我不知道如何配置 log4j,使得 debug 日志和 reportsLog 彼此分离(而不是添加)。为什么在下面的配置中,reportsLog 总是空的?

log4j.rootLogger=TRACE, stdout, debugLog


log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d [%24F:%t:%L] - %m%n


log4j.appender.debugLog=org.apache.log4j.FileAppender
log4j.appender.debugLog.File=logs/debug.log
log4j.appender.debugLog.layout=org.apache.log4j.PatternLayout
log4j.appender.debugLog.layout.ConversionPattern=%d [%24F:%t:%L] - %m%n


log4j.reportsLog=DEBUG,reportsLog
log4j.appender.reportsLog=org.apache.log4j.FileAppender
log4j.appender.reportsLog.File=logs/reports.log
log4j.appender.reportsLog.layout=org.apache.log4j.PatternLayout
log4j.appender.reportsLog.layout.ConversionPattern=%d [%24F:%t:%L] - %m%n

这是我的 Java 代码:

package test;


import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;


public class HelloLogger {


static final Logger debugLog = Logger.getLogger("debugLog");
static final Logger resultLog = Logger.getLogger("reportsLog");


public static void main(String[] args) {
PropertyConfigurator.configure("log4j.properties");
debugLog.debug("Hello debugLog message");
resultLog.debug("Hello reportsLog message");
}
}
120362 次浏览

尝试以下配置:

log4j.rootLogger=TRACE, stdout


log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d [%24F:%t:%L] - %m%n


log4j.appender.debugLog=org.apache.log4j.FileAppender
log4j.appender.debugLog.File=logs/debug.log
log4j.appender.debugLog.layout=org.apache.log4j.PatternLayout
log4j.appender.debugLog.layout.ConversionPattern=%d [%24F:%t:%L] - %m%n


log4j.appender.reportsLog=org.apache.log4j.FileAppender
log4j.appender.reportsLog.File=logs/reports.log
log4j.appender.reportsLog.layout=org.apache.log4j.PatternLayout
log4j.appender.reportsLog.layout.ConversionPattern=%d [%24F:%t:%L] - %m%n


log4j.category.debugLogger=TRACE, debugLog
log4j.additivity.debugLogger=false


log4j.category.reportsLogger=DEBUG, reportsLog
log4j.additivity.reportsLogger=false

然后相应地在 Java 代码中配置日志记录器:

static final Logger debugLog = Logger.getLogger("debugLogger");
static final Logger resultLog = Logger.getLogger("reportsLogger");

您想要输出到 stdout吗? 如果不想,请将 log4j.properties的第一行更改为:

log4j.rootLogger=OFF

去掉 stdout线。

相应地修改 log4j.properties文件:

log4j.rootLogger=TRACE,stdout
...
log4j.logger.debugLog=TRACE,debugLog
log4j.logger.reportsLog=DEBUG,reportsLog

根据需要更改每个日志记录器的日志级别。