首页 > 代码库 > log4j 每次运行生成新文件 功能
log4j 每次运行生成新文件 功能
开发中我有个需求就是,每次运行都生成新的log文件,因为我主要跑的测试,有些数据想比对还不想都放在一个文件中,这样查找起来不方便。在网上找了些发现log4j配置上没有办法满足我的需求,所以就写了个自定义类PerRunRollingFileAppender。
大致逻辑为:
读取配置文件中你配置文件的路径,遍历这个路径如果文件已经存在就重命名生成新的文件,哦对了,我这里还有在配置文件名前加了个前缀PerRunRollingFileAppender.LoggerNamePrefix,这样你可以在使用相同配置的时候,让每个测试类中生成的日志文件名不同。
note:有参考了他人代码,附上地址How to create a new log file for each time the application runs? ,但是他的可能没有测试,有个小bug,各位可以跑下亲自测下。
以下是我的代码:
package com.logger; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.log4j.FileAppender; import org.apache.log4j.Layout; import org.apache.log4j.spi.ErrorCode; public class PerRunRollingFileAppender extends FileAppender { public static String LoggerNamePrefix="default"; private static final String DOT = "."; private static final String UNDERLINE="_"; public PerRunRollingFileAppender() { } public PerRunRollingFileAppender(Layout layout, String filename, boolean append, boolean bufferedIO, int bufferSize) throws IOException { super(layout, filename, append, bufferedIO, bufferSize); } public PerRunRollingFileAppender(Layout layout, String filename, boolean append) throws IOException { super(layout, filename, append); } public PerRunRollingFileAppender(Layout layout, String filename) throws IOException { super(layout, filename); } public void activateOptions() { if (fileName != null) { try { fileName = getNewLogFileName(); setFile(fileName, fileAppend, bufferedIO, bufferSize); } catch (Exception e) { errorHandler.error("Error while activating log options", e, ErrorCode.FILE_OPEN_FAILURE); } } } private String getNewLogFileName() { if (fileName != null) { final String LEFTPARENTHESIS="("; final String RIGHTPARENTHESIS=")"; final File logFile = new File(fileName); final String fileName = logFile.getName(); final int dotIndex = fileName.indexOf(DOT); String newFileName = ""; Integer number = -1; File[] files = logFile.getParentFile().listFiles(new CustomFilter()); Pattern pattern = Pattern.compile("(?<=\\()[\\d]+"); if(files!=null&&files.length>0){ number++; for (File file : files) { Matcher matcher = pattern.matcher(file.getName()); if(matcher.find()){ if(number<Integer.valueOf(matcher.group(0))){ number=Integer.valueOf(matcher.group(0)); } } } } if (dotIndex != -1) { // the file name has an extension. so, insert the time stamp // between the file name and the extension String tempFileName = fileName.substring(0,dotIndex); final int parenthesis = tempFileName.indexOf(LEFTPARENTHESIS); if(parenthesis!=-1){ tempFileName=tempFileName.substring(parenthesis); } if(number>-1){ newFileName = LoggerNamePrefix + UNDERLINE+ tempFileName + LEFTPARENTHESIS+(++number)+RIGHTPARENTHESIS + fileName.substring(dotIndex); }else{ newFileName = LoggerNamePrefix + UNDERLINE+ tempFileName + fileName.substring(dotIndex); } } else { //是否存在文件名中存在() if(number>-1){ newFileName = LoggerNamePrefix + UNDERLINE + fileName + LEFTPARENTHESIS+(++number)+RIGHTPARENTHESIS; }else{ newFileName = LoggerNamePrefix + UNDERLINE+ fileName; } } return logFile.getParent() + File.separator + newFileName; } return null; } class CustomFilter implements FilenameFilter{ public boolean accept(File dir,String name){ File logFile = new File(fileName); String fileName = logFile.getName(); int indexDot = fileName.lastIndexOf(DOT); if(indexDot!=-1){ return name.startsWith(LoggerNamePrefix+UNDERLINE+fileName.substring(0,indexDot)); }else{ return name.startsWith(LoggerNamePrefix+UNDERLINE+fileName); } } } }
配置文件:
log4j.logger.info=info log4j.appender.info=com.logger.PerRunRollingFileAppender log4j.appender.info.File=/mnt/log/info.log log4j.appender.console.Threshold = DEBUG log4j.appender.info.layout=org.apache.log4j.PatternLayout log4j.appender.info.layout.ConversionPattern=%d{hh:mm:ss}:%p %t %l - %m%n
这样就可以啦,希望能帮助到其他人。
log4j 每次运行生成新文件 功能
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。