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

cngwdvgl  于 2022-11-06  发布在  其他
关注(0)|答案(2)|浏览(176)

我不知道如何配置我的log4j,使我的debugLog和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");
    }   
}
vof42yt1

vof42yt11#

请尝试以下配置:

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线。

ffscu2ro

ffscu2ro2#

相应地修改您的log4j.properties文件:

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

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

相关问题