2012-03-11 39 views
61

我不知道如何配置我的log4j,以便我的調試日誌和我的reportsLog是彼此分開(不添加)。爲什麼在下面的配置中,reportsLog始終是空的?如何使用一個log4j配置文件創建2個獨立的日誌文件?

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"); 
    } 
} 

回答

123

嘗試以下配置:

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

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代碼配置記錄儀你想要輸出嗎? stdout?如果沒有,將第一行的log4j.properties到:

log4j.rootLogger=OFF 

,並擺脫stdout線。

+0

謝謝!我在互聯網上搜尋了好幾個小時,卻找不到這樣的例子。謝謝!我試了一下,它工作完美。 – djangofan 2012-03-11 05:33:39

+0

幹得好!但additivty是additiv [我] ty :) – Wei 2014-11-12 13:48:24

4

修改您的log4j.properties文件相應:

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

更改爲根據您的需要每個記錄的日誌級別。

相關問題