gpt4 book ai didi

Log4j2 自定义 RolloverStrategy

转载 作者:行者123 更新时间:2023-12-02 21:21:12 24 4
gpt4 key购买 nike

有没有办法在log4j2中编写自定义RolloverStrategy?我想删除超过 14 天的旧文件,而 log4j2 目前不支持它 ( https://issues.apache.org/jira/browse/LOG4J2-524 )。

我编写了一个自定义策略并尝试实现 RolloverStrategy 接口(interface),但我没有看到它在文件翻转时被触发。

最佳答案

我成功了...我必须用 @Plugin 注释我的类,如下所示:

@org.apache.logging.log4j.core.config.plugins.Plugin(name = "DeleteMaxAgeFilesStrategy", category = "Core", printObject = true)
public class DeleteMaxAgeFilesStrategy implements RolloverStrategy {

private static final Logger logger = LoggerFactory.getLogger(DeleteMaxAgeFilesStrategy.class);

private static final int DEFAULT_MAX_AGE = 14;

private final int maxAgeIndex;

public DeleteMaxAgeFilesStrategy(int maxAgeIndex) {
this.maxAgeIndex = maxAgeIndex;
}


@Override public RolloverDescription rollover(RollingFileManager manager) throws SecurityException {
purgeMaxAgeFiles(maxAgeIndex, manager);
return null;
}


@PluginFactory
public static DeleteMaxAgeFilesStrategy createStrategy(
@PluginAttribute("maxAge") final String maxAge) {

int maxAgeIndex = DEFAULT_MAX_AGE;
if (maxAge != null) {
maxAgeIndex = Integer.parseInt(maxAge);
}
return new DeleteMaxAgeFilesStrategy(maxAgeIndex);
}

/**
* Purge files older than defined maxAge. If file older than current date - maxAge delete them or else keep it.
*
* @param maxAgeIndex maxAge Index
* @param manager The RollingFileManager
*/
private void purgeMaxAgeFiles(final int maxAgeIndex, final RollingFileManager manager) {
String filename = manager.getFileName();
File file = new File(filename);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -maxAgeIndex);
Date cutoffDate = cal.getTime();

if (file.getParentFile().exists()) {
filename = file.getName().replaceAll("\\..*", "");

File[] files = file.getParentFile().listFiles(
new StartsWithFileFilter(filename, false));

for (int i = 0; i < files.length; i++) {
try {
BasicFileAttributes attr = Files.readAttributes(files[i].toPath(), BasicFileAttributes.class);
if (new Date(attr.creationTime().toMillis()).before(cutoffDate)) {
files[i].delete();
}
} catch (Exception e) {
logger.error("Unable to delete old log files at rollover", e);
}
}
}
}

class StartsWithFileFilter implements FileFilter {
private final String startsWith;
private final boolean inclDirs;

public StartsWithFileFilter(String startsWith, boolean includeDirectories) {
super();
this.startsWith = startsWith.toUpperCase();
inclDirs = includeDirectories;
}

/*
* (non-Javadoc)
*
* @see java.io.FileFilter#accept(java.io.File)
*/
public boolean accept(File pathname) {
if (!inclDirs && pathname.isDirectory()) {
return false;
} else
return pathname.getName().toUpperCase().startsWith(startsWith);
}
}
}

这是我的 log4j2.xml 配置:

    <RollingFile name="FileOut" fileName="${sys:application.log.path}/restly-api.log"
filePattern="${sys:application.log.path}/restly-api-%d{yyyy-MM-dd}.gz">
<PatternLayout pattern="%date{yyyy/MM/dd HH:mm:ss.SSS} %-5level [%t] [%logger{36}] %msg%n"/>
<Policies>
<TimeBasedTriggeringPolicy interval="1" modulate="true"/>
</Policies>
<DeleteMaxAgeFilesStrategy maxAge="14"/>
</RollingFile>

注意:Log4j2已在2.6版本中实现了此功能

关于Log4j2 自定义 RolloverStrategy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27586378/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com