下文代码中,除了指定rootlogger输出到控制台和文件logdemo.log中之外,还定义了一个指定目的的子logger,令其日志输出到logdemo2.log文件中,同时它不继承rootlogger的输出特性。
实验环境log4j-1.2.11
log4j.properties:
#category/logger
log4j.rootLogger=debug, stdout, file
log4j.logger.SpecialPurpose=debug,file2
#Succession
log4j.additivity.SpecialPurpose=false
#to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH\:mm\:ss} %p %c %m %n
#to file#
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=logdemo.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %l %m%n
#to file2
log4j.appender.file2=org.apache.log4j.FileAppender
log4j.appender.file2.File=logdemo2.log
log4j.appender.file2.layout=org.apache.log4j.PatternLayout
log4j.appender.file2.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %l %m%n
java:
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.Logger;
public class Log4jTest {
private static Logger logger =Logger.getLogger(Log4jTest.class);
private static Log logger2 = LogFactory.getLog("SpecialPurpose");
public static void main(String[] args) {
logger.error("error");
logger.warn("warn");
logger.info("info");
logger.debug("debug");
logger2.error("error for SpecialPurpose...");
logger2.warn("warn for SpecialPurpose...");
logger2.info("info for SpecialPurpose...");
logger2.debug("debug for SpecialPurpose...");
}
}
logdemo.log和控制台文件信息:
2012-12-13 22:06:23 Log4jTest.main(Log4jTest.java:13) error
2012-12-13 22:06:23 Log4jTest.main(Log4jTest.java:14) warn
2012-12-13 22:06:23 Log4jTest.main(Log4jTest.java:15) info
2012-12-13 22:06:23 Log4jTest.main(Log4jTest.java:16) debug
logdemo2.log文件信息:
2012-12-13 22:06:23 Log4jTest.main(Log4jTest.java:18) error for SpecialPurpose...
2012-12-13 22:06:23 Log4jTest.main(Log4jTest.java:19) warn for SpecialPurpose...
2012-12-13 22:06:23 Log4jTest.main(Log4jTest.java:20) info for SpecialPurpose...
2012-12-13 22:06:23 Log4jTest.main(Log4jTest.java:21) debug for SpecialPurpose...