天天看點

Log4j 自定義輸出模闆及内容

    系統一直有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

繼續閱讀