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


74

我不知道如何配置我的log4j,以便我的debugLog和我的reportLog彼此分开(不是附加的)。为什么在以下配置中,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");
    }   
}

Answers:


138

尝试以下配置:

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界限。


谢谢!我在互联网上搜寻了几个小时,找不到这样的例子。谢谢!我尝试了一下,效果很好。
djangofan 2012年

4

相应地修改log4j.properties文件:

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

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

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.