import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.ThreadContext;
private Class clazz;
private Logger logger;
public AppLog(Class clazz) {
this.clazz = clazz;
this.logger = LogManager.getLogger(this.clazz);
}
lo4j2.properties
name = PropertiesConfig
filter.threshold.type = ThresholdFilter
filter.threshold.level = INFO
#root
rootLogger=info,console,mian_log,custom_log
rootLogger.appenderRef.stdout.ref = STDOUT
rootLogger.level =INFO
#console
appender.console.type = Console
appender.console.name = STDOUT
appender.console.layout.type = PatternLayout //通過ThreadContext.put("hostAddr", "value")添加進去
appender.console.layout.pattern = %m%n%d{yyyy/MM/dd HH:mm:ss,SSS} %-5p %X{hostAddr} [%X{sessionId}] %m [%c]%n
appender.console.filter.threshold.type = ThresholdFilter
appender.console.filter.threshold.level = INFO
logger.console.name = mujinetstore.batch
#mian_log -> aaa.bbb.ccc
appender.mian_log.type = RollingFile
appender.mian_log.name = mian_log
appender.mian_log.fileName = /xxx/aaaa/mian_log.log //log路徑
appender.mian_log.filePattern = /xxx/aaaa/mian_log-%d{MM-dd-yyyy}.log.gz
appender.mian_log.layout.type = PatternLayout
appender.mian_log.layout.pattern = %d{yyyy/MM/dd HH:mm:ss,SSS} %-5p %X{hostAddr} [%X{sessionId}] %m [%c]%n
appender.mian_log.policies.type = Policies
logger.mian_log.name = aaa.bbb.ccc//指定這個包下面的所有log
logger.mian_log.level = INFO
logger.mian_log.additivity = true
logger.mian_log.appenderRef.rolling.ref = mian_log
#custom_log -> customLog.log
appender.custom_log.type = RollingFile
appender.custom_log.name = custom_log
appender.custom_log.fileName = /xxx/aaaa/customLog.log
appender.custom_log.filePattern = /xxx/aaaa/customLog-%d{MM-dd-yyyy}.log.gz
appender.custom_log.layout.type = PatternLayout
appender.custom_log.layout.pattern = "%d{yyyy/MM/dd HH:mm:ss}",%m%n
appender.custom_log.policies.type = Policies
logger.back_trace_log.name = customLog //指定"customLog"
logger.back_trace_log.level = INFO
logger.back_trace_log.additivity = true
logger.back_trace_log.appenderRef.rolling.ref = custom_log
//customLog
static final String name = "customLog";
public static Logger logger = LogManager.getLogger(name);
ThreadContext.put("hostAddr", "value");
MDC和ThreadContext
MDC使用Map機制來存儲信息,信息以key/value對的形式存儲在Map中。
使用Servlet Filter在接收到請求時,生成UUID填充MDC。在log4j的配置中就可以使用%X{key}打印MDC中的內容,從而識別出同一次請求中的log
在log4j 2.0 中,使用ThreadContext代替了MDC