多个不相关的日志文件,包含log4j和commons日志记录

时间:2011-02-09 05:15:40

标签: java log4j apache-commons-logging

我希望我的应用有4个日志文件。其中三个日志文件是典型的log4j Info,Warn和Error日志。第4个日志文件完全不相关,用于记录一些数据。

我的log4j.properties文件如下所示:

log4j.threshold=ALL
log4j.rootLogger=ALL, InfoAppender, WarnAppender, ErrorAppender
log4j.DATA_LOGGER=INFO, DataAppender
log4j.additivity.DATA_LOGGER = false

log4j.appender.DataAppender=org.apache.log4j.DailyRollingFileAppender
log4j.appender.DataAppender.File=/app_logs/data.log

log4j.appender.InfoAppender=org.apache.log4j.DailyRollingFileAppender
log4j.appender.InfoAppender.File=/app_logs/info.log

log4j.appender.WarnAppender=org.apache.log4j.DailyRollingFileAppender
log4j.appender.WarnAppender.File=/app_logs/warn.log

log4j.appender.ErrorAppender=org.apache.log4j.DailyRollingFileAppender
log4j.appender.ErrorAppender.File=/app_logs/error.log

我的Java代码如下所示:

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

private static final Log LOG = LogFactory.getLog(SomeClassInMyApp.class);
private static final Log DATA_LOG = LogFactory.getLog("DATA_LOGGER");

private static void foo() {
    LOG.info("Hello");
    DATA_LOG.info("Some data");
}

当我运行它时,“Hello”文本被正确写入info.log文件。但是从不创建或写入data.log文件。

为什么DATA_LOG.info(“Some data”)行没有写入data.log文件,我需要做些什么代码更改才能实现呢?

1 个答案:

答案 0 :(得分:2)

commons应该也可以,你可以尝试这个吗

   import org.apache.log4j.Logger;
   ...
   ...
   Logger log = Logger.getLogger("DATA_LOGGER");
   ...
   ...
   log.info("my data");

而不是

   import org.apache.commons.logging.Log;

更新刚刚测试过此代码有效:

<强> log4j.properties

log4j.rootLogger = DEBUG, R

log4j.appender.R=org.apache.log4j.DailyRollingFileAppender
log4j.appender.R.File=E:/testroot.log

log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%d{DATE} %-5p %c:%L %x - %m%n


##########################################################################
################## Appender for Other Logger  ############################
##########################################################################
log4j.logger.TestLog=DEBUG, cache
log4j.additivity.TestLog=false

log4j.appender.cache=org.apache.log4j.DailyRollingFileAppender
log4j.appender.cache.File=E:/testcache.log
log4j.appender.cache.layout=org.apache.log4j.PatternLayout
log4j.appender.cache.layout.ConversionPattern=%d{dd/MM/yyyy HH:mm:ss} %c %m%n

<强> Test Code

private static final Logger DATA_LOG = Logger.getLogger("TestLog");
private static final Logger LOG = Logger.getLogger(Test.class);

public static final void main(String[] args){
    LOG.error("MSG1");
    DATA_LOG.error("MSG2");
}

<强> Output

testroot.log
09 Feb 2011 12:18:29,671 ERROR in.naishe.so.Test:11  - MSG1

testcache.log
09/02/2011 12:18:29 TestLog MSG2

你错过了什么吗?