logback FixedWindowRollingPolicy固定窗口算法重命名文件滚动策略

 更新时间:2023年11月09日 09:17:22   作者:codecraft  
这篇文章主要介绍了FixedWindowRollingPolicy根据logback 固定窗口算法重命名文件滚动策略源码解读,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

本文主要研究一下logback的FixedWindowRollingPolicy

RollingPolicy

ch/qos/logback/core/rolling/RollingPolicy.java

/**
 * A <code>RollingPolicy</code> is responsible for performing the rolling over
 * of the active log file. The <code>RollingPolicy</code> is also responsible
 * for providing the <em>active log file</em>, that is the live file where
 * logging output will be directed.
 * 
 * @author Ceki G&uuml;lc&uuml;
 */
public interface RollingPolicy extends LifeCycle {
    /**
     * Rolls over log files according to implementation policy.
     * 
     * <p>
     * This method is invoked by {@link RollingFileAppender}, usually at the behest
     * of its {@link TriggeringPolicy}.
     * 
     * @throws RolloverFailure Thrown if the rollover operation fails for any
     *                         reason.
     */
    void rollover() throws RolloverFailure;
    /**
     * Get the name of the active log file.
     * 
     * <p>
     * With implementations such as {@link TimeBasedRollingPolicy}, this method
     * returns a new file name, where the actual output will be sent.
     * 
     * <p>
     * On other implementations, this method might return the FileAppender's file
     * property.
     */
    String getActiveFileName();
    /**
     * The compression mode for this policy.
     * 
     * @return
     */
    CompressionMode getCompressionMode();
    /**
     * This method allows RollingPolicy implementations to be aware of their
     * containing appender.
     * 
     * @param appender
     */
    void setParent(FileAppender<?> appender);
}
RollingPolicy接口定义了rollover、getActiveFileName、getCompressionMode、setParent方法

RollingPolicyBase

ch/qos/logback/core/rolling/RollingPolicyBase.java

/**
 * Implements methods common to most, it not all, rolling policies. Currently
 * such methods are limited to a compression mode getter/setter.
 * 
 * @author Ceki G&uuml;lc&uuml;
 */
public abstract class RollingPolicyBase extends ContextAwareBase implements RollingPolicy {
    protected CompressionMode compressionMode = CompressionMode.NONE;
    FileNamePattern fileNamePattern;
    // fileNamePatternStr is always slashified, see setter
    protected String fileNamePatternStr;
    private FileAppender<?> parent;
    // use to name files within zip file, i.e. the zipEntry
    FileNamePattern zipEntryFileNamePattern;
    private boolean started;
    /**
     * Given the FileNamePattern string, this method determines the compression mode
     * depending on last letters of the fileNamePatternStr. Patterns ending with .gz
     * imply GZIP compression, endings with '.zip' imply ZIP compression. Otherwise
     * and by default, there is no compression.
     * 
     */
    protected void determineCompressionMode() {
        if (fileNamePatternStr.endsWith(".gz")) {
            addInfo("Will use gz compression");
            compressionMode = CompressionMode.GZ;
        } else if (fileNamePatternStr.endsWith(".zip")) {
            addInfo("Will use zip compression");
            compressionMode = CompressionMode.ZIP;
        } else {
            addInfo("No compression will be used");
            compressionMode = CompressionMode.NONE;
        }
    }
    //......
}
RollingPolicyBase定义了compressionMode、fileNamePattern、fileNamePatternStr、parent、zipEntryFileNamePattern、started;
determineCompressionMode方法会根据fileNamePatternStr的后缀来判断,默认支持gz、zip

FixedWindowRollingPolicy

ch/qos/logback/core/rolling/FixedWindowRollingPolicy.java

public class FixedWindowRollingPolicy extends RollingPolicyBase {
    static final String FNP_NOT_SET = "The \"FileNamePattern\" property must be set before using FixedWindowRollingPolicy. ";
    static final String PRUDENT_MODE_UNSUPPORTED = "See also " + CODES_URL + "#tbr_fnp_prudent_unsupported";
    static final String SEE_PARENT_FN_NOT_SET = "Please refer to " + CODES_URL + "#fwrp_parentFileName_not_set";
    int maxIndex;
    int minIndex;
    RenameUtil util = new RenameUtil();
    Compressor compressor;
    public static final String ZIP_ENTRY_DATE_PATTERN = "yyyy-MM-dd_HHmm";
    /**
     * It's almost always a bad idea to have a large window size, say over 20.
     */
    private static int MAX_WINDOW_SIZE = 20;
    public FixedWindowRollingPolicy() {
        minIndex = 1;
        maxIndex = 7;
    }
    //......
}
FixedWindowRollingPolicy继承了RollingPolicyBase,他定义了minIndex、maxIndex、compressor属性

start

public void start() {
        util.setContext(this.context);
        if (fileNamePatternStr != null) {
            fileNamePattern = new FileNamePattern(fileNamePatternStr, this.context);
            determineCompressionMode();
        } else {
            addError(FNP_NOT_SET);
            addError(CoreConstants.SEE_FNP_NOT_SET);
            throw new IllegalStateException(FNP_NOT_SET + CoreConstants.SEE_FNP_NOT_SET);
        }
        if (isParentPrudent()) {
            addError("Prudent mode is not supported with FixedWindowRollingPolicy.");
            addError(PRUDENT_MODE_UNSUPPORTED);
            throw new IllegalStateException("Prudent mode is not supported.");
        }
        if (getParentsRawFileProperty() == null) {
            addError("The File name property must be set before using this rolling policy.");
            addError(SEE_PARENT_FN_NOT_SET);
            throw new IllegalStateException("The \"File\" option must be set.");
        }
        if (maxIndex < minIndex) {
            addWarn("MaxIndex (" + maxIndex + ") cannot be smaller than MinIndex (" + minIndex + ").");
            addWarn("Setting maxIndex to equal minIndex.");
            maxIndex = minIndex;
        }
        final int maxWindowSize = getMaxWindowSize();
        if ((maxIndex - minIndex) > maxWindowSize) {
            addWarn("Large window sizes are not allowed.");
            maxIndex = minIndex + maxWindowSize;
            addWarn("MaxIndex reduced to " + maxIndex);
        }
        IntegerTokenConverter itc = fileNamePattern.getIntegerTokenConverter();
        if (itc == null) {
            throw new IllegalStateException(
                    "FileNamePattern [" + fileNamePattern.getPattern() + "] does not contain a valid IntegerToken");
        }
        if (compressionMode == CompressionMode.ZIP) {
            String zipEntryFileNamePatternStr = transformFileNamePatternFromInt2Date(fileNamePatternStr);
            zipEntryFileNamePattern = new FileNamePattern(zipEntryFileNamePatternStr, context);
        }
        compressor = new Compressor(compressionMode);
        compressor.setContext(this.context);
        super.start();
    }
start方法先根据fileNamePattern来创建FileNamePattern,然后判断压缩模式,然后校验minIndex及maxIndex,要求相差不能超过MAX_WINDOW_SIZE(默认值为20),之后判断如果是zip模式的则创建zipEntryFileNamePattern,最后根据压缩模式创建compressor

rollover

public void rollover() throws RolloverFailure {
        // Inside this method it is guaranteed that the hereto active log file is
        // closed.
        // If maxIndex <= 0, then there is no file renaming to be done.
        if (maxIndex >= 0) {
            // Delete the oldest file, to keep Windows happy.
            File file = new File(fileNamePattern.convertInt(maxIndex));
            if (file.exists()) {
                file.delete();
            }
            // Map {(maxIndex - 1), ..., minIndex} to {maxIndex, ..., minIndex+1}
            for (int i = maxIndex - 1; i >= minIndex; i--) {
                String toRenameStr = fileNamePattern.convertInt(i);
                File toRename = new File(toRenameStr);
                // no point in trying to rename a nonexistent file
                if (toRename.exists()) {
                    util.rename(toRenameStr, fileNamePattern.convertInt(i + 1));
                } else {
                    addInfo("Skipping roll-over for inexistent file " + toRenameStr);
                }
            }
            // move active file name to min
            switch (compressionMode) {
            case NONE:
                util.rename(getActiveFileName(), fileNamePattern.convertInt(minIndex));
                break;
            case GZ:
                compressor.compress(getActiveFileName(), fileNamePattern.convertInt(minIndex), null);
                break;
            case ZIP:
                compressor.compress(getActiveFileName(), fileNamePattern.convertInt(minIndex),
                        zipEntryFileNamePattern.convert(new Date()));
                break;
            }
        }
    }
rollover方法从maxIndex-1开始到minIndex,把这些文件名的序号加1,之后根据压缩模式判断,如果不压缩则把当前文件名重名为minIndex,若是gz压缩则把当前文件压缩然后命名为minIndex,若是zip压缩则把当前文件压缩然后命名为minIndex加上日期

小结

logback的FixedWindowRollingPolicy继承了RollingPolicyBase,实现了RollingPolicy接口,该接口定义了rollover、getActiveFileName、getCompressionMode、setParent方法,其中FixedWindowRollingPolicy的rollover的实现是根据minIndex及maxIndex来的,要求maxIndex及minIndex相差不能超过20,rollover的时候从maxIndex-1开始到minIndex,把这些文件名的序号加1,然后当前文件重命名为minIndex,其中还配合压缩模式进行压缩处理。

以上就是logback FixedWindowRollingPolicy固定窗口算法重命名文件滚动策略的详细内容,更多关于logback FixedWindowRollingPolicy的资料请关注脚本之家其它相关文章!

相关文章

  • SpringBoot搭建全局异常拦截

    SpringBoot搭建全局异常拦截

    这篇文章主要介绍了SpringBoot搭建全局异常拦截,本文通过详细的介绍与代码的展示,详细的说明了如何搭建该项目,包括创建,启动和测试步骤,需要的朋友可以参考下
    2021-06-06
  • 9种Java单例模式详解(推荐)

    9种Java单例模式详解(推荐)

    这篇文章主要介绍了9种Java单例模式详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-03-03
  • Java泛型详解

    Java泛型详解

    本文给大家汇总介绍了下java中的泛型的相关资料,包括引入泛型机制的原因,泛型类,泛型方法,泛型的实现以及泛型的注意事项,非常的详细,有需要的小伙伴可以参考下
    2016-03-03
  • Java设计通用的返回数据格式过程讲解

    Java设计通用的返回数据格式过程讲解

    现在很多的项目server端返回client端的数据多数以JSON格式返回,同时结合其它需要,通常加一下状态码和信息之类,给前端处理带来很大的方便,这篇文章就用Java设计了通用的返回数据格式,感兴趣的同学可以参考下文
    2023-05-05
  • 解析SpringBoot中@Autowire注解的实现原理

    解析SpringBoot中@Autowire注解的实现原理

    在开发Java项目时,依赖注入是一种常见的实现方式,SpringBoot框架通过@Autowired注解来实现依赖注入的功能,本文将介绍SpringBoot中 Autowired注解实现的原理
    2023-06-06
  • mybatis的dtd约束文件及配置文件xml自动提示操作

    mybatis的dtd约束文件及配置文件xml自动提示操作

    这篇文章主要介绍了mybatis的dtd约束文件及配置文件xml自动提示操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-12-12
  • Spring中@Autowired注解作用在方法上和属性上说明

    Spring中@Autowired注解作用在方法上和属性上说明

    这篇文章主要介绍了Spring中@Autowired注解作用在方法上和属性上说明,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-11-11
  • JVM系列之:再谈java中的safepoint说明

    JVM系列之:再谈java中的safepoint说明

    这篇文章主要介绍了JVM系列之:再谈java中的safepoint说明,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-09-09
  • 详解SpringCloud微服务架构之Hystrix断路器

    详解SpringCloud微服务架构之Hystrix断路器

    本篇文章主要介绍了详解SpringCloud微服务架构之Hystrix断路器,Hystrix是一个库,通过添加延迟容差和容错逻辑来帮助您控制这些分布式服务之间的交互,有兴趣的可以了解一下
    2018-01-01
  • java使用for循环输出杨辉三角

    java使用for循环输出杨辉三角

    杨辉三角形由数字排列,可以把它看做一个数字表,其基本特性是两侧数值均为1,其他位置的数值是其正上方的数字与左上角数值之和,下面是java使用for循环输出包括10行在内的杨辉三角形
    2014-02-02

最新评论