有如下的log4j.properties配置
log4j.rootLogger=ERROR,STDOUT
log4j.appender.STDOUT=org.apache.log4j.ConsoleAppender
log4j.appender.STDOUT.layout=org.apache.log4j.PatternLayout
log4j.appender.STDOUT.layout.ConversionPattern=%d %-5p [%t] (%F:%L) - %m%n
log4j.appender.fileAppender1=org.apache.log4j.FileAppender
log4j.appender.fileAppender2=org.apache.log4j.FileAppender
#省略了fileAppender1和fileAppender2的layout和layout.ConversionPattern定义,和STDOUT一样的,如果你要测试,那么将STDOUT拷一份就好了
log4j.logger.org.springframework=info,fileAppender1
log4j.logger.org.springframework.web=info,fileAppender2
那么对于org.springframework.web包下的日志,会输出到STDOUT,fileAppender1,fileAppender2这三个appender中,如果只想输出到fileAppender2中,只需添加 log4j.additivity.org.springframework.web=false 就好了
参考源码
public void org.apache.log4j.Category.callAppenders(LoggingEvent event) {
int writes = 0;
for(Category c = this; c != null; c=c.parent) {
// Protected against simultaneous call to addAppender, removeAppender,...
synchronized(c) {
if(c.aai != null) {
writes += c.aai.appendLoopOnAppenders(event);
}
if(!c.additive) {
break;
}
}
}
if(writes == 0) {
repository.emitNoAppenderWarning(this);
}
}