log4j按级别输出日志文件

时间:2021-11-27 07:29:50

log4j.properties:

BASE_DIR= /home/admin/preprocess-tmc-city/logs

log4j.rootLogger=debug,stdout,debug,info,warn,error  
log4j.appender.stdout=org.apache.log4j.ConsoleAppender  
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout  
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c:%L] %t - <%m>%n
   
log4j.logger.debug=debug  
log4j.appender.debug=com.autonavi.tinfo.traffic.tmc.config.TMCRollingAppender  
log4j.appender.debug.layout=org.apache.log4j.PatternLayout  
log4j.appender.debug.layout.ConversionPattern=%d %p [%c:%L] %t - <%m>%n
#log4j.appender.debug.datePattern='.'yyyy-MM-dd  
log4j.appender.debug.Threshold = DEBUG   
log4j.appender.debug.append=true  
log4j.appender.debug.MaxBackupIndex=10
log4j.appender.debug.MaxFileSize=500MB
log4j.appender.debug.File=${BASE_DIR}/debug/debug.log  
 
log4j.logger.info=info  
log4j.appender.info=com.autonavi.tinfo.traffic.tmc.config.TMCRollingAppender
log4j.appender.info.layout=org.apache.log4j.PatternLayout  
log4j.appender.info.layout.ConversionPattern=%d %p [%c:%L] %t - <%m>%n
#log4j.appender.info.datePattern='.'yyyy-MM-dd  
log4j.appender.info.Threshold = INFO   
log4j.appender.info.append=true  
log4j.appender.info.MaxBackupIndex=10
log4j.appender.info.MaxFileSize=500MB
log4j.appender.info.File=${BASE_DIR}/info/info.log

log4j.logger.warn=warn
log4j.appender.warn=com.autonavi.tinfo.traffic.tmc.config.TMCRollingAppender
log4j.appender.warn.layout=org.apache.log4j.PatternLayout
log4j.appender.warn.layout.ConversionPattern=%d %p [%c:%L] %t - <%m>%n
#log4j.appender.warn.datePattern='.'yyyy-MM-dd
log4j.appender.warn.Threshold = WARN
log4j.appender.warn.append=true
log4j.appender.warn.MaxBackupIndex=10
log4j.appender.warn.MaxFileSize=500MB
log4j.appender.warn.File=${BASE_DIR}/warn/warn.log

log4j.logger.error=error  
log4j.appender.error=com.autonavi.tinfo.traffic.tmc.config.TMCRollingAppender  
log4j.appender.error.layout=org.apache.log4j.PatternLayout  
log4j.appender.error.layout.ConversionPattern=%d %p [%c:%L] %t - <%m>%n
#log4j.appender.error.datePattern='.'yyyy-MM-dd  
log4j.appender.error.Threshold = ERROR   
log4j.appender.error.append=true  
log4j.appender.error.MaxBackupIndex=10
log4j.appender.error.MaxFileSize=500MB
log4j.appender.error.File=${BASE_DIR}/error/error.log

定义自己的Appender类,继承DailyRollingFileAppender,改写针对Threshold 的设置说明。

重写 isAsSevereAsThreshold(Priority priority)方法

package com.autonavi.tinfo.traffic.tmc.config;

import org.apache.log4j.Priority;
import org.apache.log4j.RollingFileAppender; public class TMCRollingAppender extends RollingFileAppender {
@Override
public boolean isAsSevereAsThreshold(Priority priority) {
//只判断是否相等,而不判断优先级
return this.getThreshold().equals(priority);
}
}