Log4j2 自定义翻转策略

Aru*_*uri 2 log4j2

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

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

Aru*_*uri 5

我让它工作了……我必须用@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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的 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>
Run Code Online (Sandbox Code Playgroud)

注意:Log4j2 在 2.6 版本中已经实现了这个特性