系统一直有log4j打印日志,但是需要在日志打印上加上系统的版本信息,因为生产系统的频繁升级的情况下会出现一天的日志打印乱输出的情况,也是为了方便定位问题吧。在这里之前考虑了下对DailyRollingFileAppender ConsoleAppender进行extend操作,发现这种要对两个appender进行实现,有些繁琐。
接下来就考虑改造org.apache.log4j.PatternLayout;对其进行继承,并重写它的所有方法。
import org.apache.log4j.MDC;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.helpers.PatternParser;
import org.apache.log4j.spi.LoggingEvent;
import org.jeecgframework.core.util.PropertiesUtil;
public class LogCustomLayout extends PatternLayout {
private static String systemVersion = "v1.0";
static{
PropertiesUtil propertiesUtil = new PropertiesUtil("sysConfig.properties");
systemVersion = propertiesUtil.readProperty("system.platf.version");
}
public LogCustomLayout() {
super();
}
public LogCustomLayout(String pattern) {
super(pattern);
}
@Override
public void setConversionPattern(String conversionPattern) {
super.setConversionPattern(conversionPattern);
}
@Override
public String getConversionPattern() {
return super.getConversionPattern();
}
@Override
public void activateOptions() {
super.activateOptions();
}
@Override
public boolean ignoresThrowable() {
return super.ignoresThrowable();
}
@Override
protected PatternParser createPatternParser(String pattern) {
return super.createPatternParser(pattern);
}
@Override
public String format(LoggingEvent event) {
MDC.put("systemVersion",systemVersion);
return super.format(event);
}
}
log4j.properties 修改layout配置:
log4j.rootLogger=info,A1,R
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.Target=System.out
log4j.appender.A1.layout=com.jaminzhang.common.logging.LogCustomLayout
log4j.appender.A1.layout.ConversionPattern=%X{systemVersion}--[%p][%d{yyyy-MM-dd HH\:mm\:ss,SSS}]%m%n
log4j.appender.R=org.apache.log4j.DailyRollingFileAppender
log4j.appender.R.File=../logs/test_log_.txt
log4j.appender.R.layout=com.jaminzhang.common.logging.LogCustomLayout
log4j.appender.R.Append = true
log4j.appender.R.ImmediateFlush = true
log4j.appender.R.DatePattern = '.' yyyy - MM - dd '.txt'
log4j.appender.R.layout.ConversionPattern=%X{systemVersion}--[%p][%d{yyyy-MM-dd HH\:mm\:ss,SSS}][%c]%m%n
bingo!
参考blog感谢:
https://blog.csdn.net/userwyh/article/details/52862216
https://blog.csdn.net/userwyh/article/details/52862216