doclist 阅读(37) 评论(0)

新年之际,碰到线上日志文件消失问题,借此机会解读了一下log4j日志的工作原理,以此记录一下

首先项目中的log4j.properties配置内容

log4j.rootLogger=info,logfile
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d %l %-5p - %m%n
log4j.appender.logfile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.logfile.File=/opt/appstack/apache-tomcat/logs/XX/XX.log
log4j.appender.logfile.maxBackupIndex=30
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern====%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %logger Line:%-3L - %msg%n

DailyRollingFileAppender相关类图

 

log4j日志工作原理

一、读取初始化日志配置信息

private final Logger log = LoggerFactory.getLogger(this.getClass());

log对象获取工作原理

org.slf4j.LoggerFactory#getLogger(java.lang.String)

  org.slf4j.impl.Log4jLoggerFactory#getLogger

  

  所以这里的log对象是Log4jLoggerAdapter类型

  

  LogManager的静态有对log4j.properties读取解析

 

 二、代码日志记录工作原理

打印记录

log.info("开始时间:{},访问路径:/api/user/login,手机号:{},fv:{},fsv:{},登录参数信息:{}", start, loginDTO.getPhone(),
loginDTO.getFv(), loginDTO.getFsv(), JSON.toJSONString(loginDTO));

 所有的日志级别记录,最终都是进入到以下方法

org.apache.log4j.Category#log(java.lang.String, org.apache.log4j.Priority, java.lang.Object, java.lang.Throwable)

 

整个日志记录执行工作原理如下:

-->org.slf4j.impl.Log4jLoggerAdapter#info(java.lang.String, java.lang.Object...)

---->org.apache.log4j.Category#log(java.lang.String, org.apache.log4j.Priority, java.lang.Object, java.lang.Throwable)

------>org.apache.log4j.Category#forcedLog(java.lang.String, org.apache.log4j.Priority, java.lang.Object, java.lang.Throwable)

-------->org.apache.log4j.Category#callAppenders(org.apache.log4j.spi.LoggingEvent)

---------->org.apache.log4j.helpers.AppenderAttachableImpl#appendLoopOnAppenders(org.apache.log4j.spi.LoggingEvent)

------------>org.apache.log4j.AppenderSkeleton#doAppend(org.apache.log4j.spi.LoggingEvent)

-------------->org.apache.log4j.WriterAppender#append(org.apache.log4j.spi.LoggingEvent)

---------------->org.apache.log4j.DailyRollingFileAppender#subAppend(org.apache.log4j.spi.LoggingEvent)

------------------>org.apache.log4j.WriterAppender#subAppend(org.apache.log4j.spi.LoggingEvent)

-------------------->org.apache.log4j.helpers.QuietWriter#write(java.lang.String)

 

org.apache.log4j.DailyRollingFileAppender#subAppend(org.apache.log4j.spi.LoggingEvent)方法代码逻辑

protected void subAppend( LoggingEvent event ){

  long n = System.currentTimeMillis();
  if ( n >= nextCheck )
  {
    now.setTime( n );
    nextCheck = rc.getNextCheckMillis( now );
    try {
      rollOver();
    }catch ( IOException ioe ) {
      if ( ioe instanceof InterruptedIOException ){
        Thread.currentThread().interrupt();
      }
      LogLog.error( "rollOver() failed.", ioe );
    }
  }
  super.subAppend( event );
}

如果是当前时间到了下次生成新的日志文件时间时,执行rollOver方法,该方法包含对之前归档的日志文件处理以及生成新的日志文件