首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Log4j2自定义RolloverStrategy

Log4j2自定义RolloverStrategy
EN

Stack Overflow用户
提问于 2014-12-21 03:07:25
回答 1查看 2.3K关注 0票数 2

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

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-12-23 22:26:32

我让它正常工作.我不得不用@Plugin注释我的类,如下所示:

代码语言:javascript
复制
@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配置:

代码语言:javascript
复制
    <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版本的中实现了这个特性

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27586378

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档