log4j按日期和文件大小生成日志文件

  • Post author:
  • Post category:其他




log4j按日期和文件大小生成日志文件

	最近在做日志输出保存,按日期和文件大小生成日志文件,比如说生成的日志文件路径为.../20190820/log.log,log1.log,log2.log。其20190820下的log文件大小相同
	由于框架比较老,ssh,导致测试的时候能生成日志文件,但是内容为空,最后发现是log4j的jar包冲突的原因,特别注意一下
  1. log4j.properties配置
log4j.rootLogger=INFO,Console,File
#定义日志输出目的地为控制台
log4j.appender.Console=org.apache.log4j.ConsoleAppender
#log4j.appender.Console.Target=System.out
log4j.appender.Console.Threshold=INFO
#可以灵活地指定日志输出格式,下面一行是指定具体的格式
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n
#文件大小到达指定尺寸的时候产生一个新的文件
#log4j.appender.File=org.apache.log4j.RollingFileAppender
log4j.appender.File=net.northking.util.rizhi.MyRollingFileAppender
log4j.appender.File.encoding=UTF-8
#指定输出目录
log4j.appender.File.File=logs/uip.log
#定义文件最大大小
log4j.appender.File.MaxFileSize=20MB
#定义最大可生成文件个数
log4j.appender.File.MaxBackupIndex=20
log4j.appender.File.Append=true
# 输出所以日志,如果换成DEBUG表示输出DEBUG以上级别日志
log4j.appender.File.Threshold=ALL
log4j.appender.File.layout=org.apache.log4j.PatternLayout
log4j.appender.File.layout.ConversionPattern=[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n

  1. web.xml配置
<context-param>
    <param-name>log4jConfigLocation</param-name>
    <param-value>classpath:log4j.properties</param-value>
  </context-param>
  <context-param>
    <param-name>log4jRefreshInterval</param-name>
    <param-value>60000</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
  </listener>
  1. 自定义类继承RollingFileAppender,生成我们想要的格式
package net.northking.util.rizhi;

import org.apache.log4j.RollingFileAppender;
import org.apache.log4j.helpers.CountingQuietWriter;
import org.apache.log4j.helpers.LogLog;
import org.apache.log4j.spi.LoggingEvent;

import java.io.File;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 自定义类继承RollingFileAppender,
 * 按日期生成文件夹,日志放在日期文件夹下
 */
public class MyRollingFileAppender extends RollingFileAppender{
    private long nextRollover = 0;
    private static SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");

    public void rollOver() {
        File target;
        File file;

        if (qw != null) {
            long size = ((CountingQuietWriter) qw).getCount();
            nextRollover = size + maxFileSize;
        }
        LogLog.debug("maxBackupIndex=" + maxBackupIndex);

        boolean renameSucceeded = true;
        if (maxBackupIndex > 0) {
            // 所有文件名序号加1
            for (int i = maxBackupIndex - 1; i >= 1 && renameSucceeded; i--) {
                file = new File(genFileName(fileName, i));
                if (file.exists()) {
                    target = new File(genFileName(fileName, i + 1));
                    renameSucceeded = file.renameTo(target);
                }
            }

            if (renameSucceeded) {
                target = new File(genFileName(fileName, 1));
                this.closeFile();
                file = new File(fileName);
                renameSucceeded = file.renameTo(target);
                if (!renameSucceeded) {
                    try {
                        this.setFile(fileName, true, bufferedIO, bufferSize);
                    } catch (IOException e) {
                        if (e instanceof InterruptedIOException) {
                            Thread.currentThread().interrupt();
                        }
                        LogLog.error("setFile(" + fileName
                                + ", true) call failed.", e);
                    }
                }
            }
        }
        if (renameSucceeded) {
            try {
                this.setFile(fileName, false, bufferedIO, bufferSize);
                nextRollover = 0;
            } catch (IOException e) {
                if (e instanceof InterruptedIOException) {
                    Thread.currentThread().interrupt();
                }
                LogLog.error("setFile(" + fileName + ", false) call failed.", e);
            }
        }
    }

    private String genFileName(String name, int index) {
        String val = "_"+df.format(new Date())+"_";
        String fileName = "";
        if (index > 0) {
            String num = index < maxBackupIndex ? "0" + index : String.valueOf(index);
            fileName = name.replace(".log", "") + val + num + ".log";
        } else {
            fileName = name;
        }
        return fileName;
    }

    protected void subAppend(LoggingEvent event) {
        super.subAppend(event);
        boolean flag = false;
        String[] _files = fileName.split("/");
        int len = _files.length;
        String file_name = _files[len-2];
        String new_file_name = df.format(new Date());
        if(!file_name.equals(new_file_name)){
            flag = true;
            fileName = fileName.replace(file_name, new_file_name);
        }
        if (fileName != null && qw != null) {
            long size = ((CountingQuietWriter) qw).getCount();
            if(flag){
                size = 0L;
            }
            if ((size >= maxFileSize && size >= nextRollover) || flag) {
                rollOver();
            }
        }
    }

    public void setFile(String file) {
        String val = file.trim();
        fileName = val.substring(0, val.lastIndexOf("/"))+"/"+df.format(new Date())+
                val.substring(val.lastIndexOf("/"), val.length());
    }
}



版权声明:本文为weixin_44446164原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。