ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy Java Examples

The following examples show how to use ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SpacedLogbackSystem.java    From spring-cloud-formula with Apache License 2.0 5 votes vote down vote up
private void setRollingPolicy(RollingFileAppender<ILoggingEvent> appender, Space space, String path, String file) {
        SizeAndTimeBasedRollingPolicy<ILoggingEvent> rollingPolicy = new SizeAndTimeBasedRollingPolicy<>();
        String dirName = new File(path, file).getParent();
        rollingPolicy.setFileNamePattern(dirName + "/%d{dd,aux}/" + file + ".%d{yyyy-MM-dd-HH}.%i");
        String maxFileSize = space.getSpec().getMaxFileSize() != null ? space.getSpec().getMaxFileSize() :
                space.getDefaultSpec().getMaxFileSize() != null ? space.getDefaultSpec().getMaxFileSize() :
                        DEFAULT_FILE_SIZE;
        setMaxFileSize(rollingPolicy, maxFileSize);

        // total size cap
        String totalSizeCap = space.getSpec().getTotalSizeCap() != null ? space.getSpec().getTotalSizeCap() :
                space.getDefaultSpec().getTotalSizeCap() != null ? space.getDefaultSpec().getTotalSizeCap() :
                        DEFAULT_TOTAL_SIZE_CAP;

        setTotalSizeCap(rollingPolicy, totalSizeCap);

        int maxHistory = space.getSpec().getMaxHistory() != null ? space.getSpec().getMaxHistory() :
                space.getDefaultSpec().getMaxHistory() != null ? space.getDefaultSpec().getMaxHistory() :
                        DEFAULT_MAX_HISTORY;
        rollingPolicy.setMaxHistory(maxHistory);

        appender.setRollingPolicy(rollingPolicy);
        rollingPolicy.setCleanHistoryOnStart(true);
        rollingPolicy.setParent(appender);
//        rollingPolicy.setCleanHistoryOnStart(true);
        start(rollingPolicy);
    }
 
Example #2
Source File: SpacedLogbackSystem.java    From spring-cloud-formula with Apache License 2.0 5 votes vote down vote up
private void setTotalSizeCap(SizeAndTimeBasedRollingPolicy<ILoggingEvent> rollingPolicy,
                             String totalSizeCap) {
    try {
        rollingPolicy.setContext(context);
        rollingPolicy.setTotalSizeCap(FileSize.valueOf(totalSizeCap));
    } catch (NoSuchMethodError ex) {
        // Logback < 1.1.8 used String configuration
        // copy from setMaxFileSize
        Method method = ReflectionUtils.findMethod(
                SizeAndTimeBasedRollingPolicy.class, "setTotalSizeCap", String.class);
        ReflectionUtils.invokeMethod(method, rollingPolicy, totalSizeCap);
    }
}
 
Example #3
Source File: SpacedLogbackSystem.java    From spring-cloud-formula with Apache License 2.0 5 votes vote down vote up
private void setMaxFileSize(SizeAndTimeBasedRollingPolicy<ILoggingEvent> rollingPolicy,
                            String maxFileSize) {
    try {
        rollingPolicy.setMaxFileSize(FileSize.valueOf(maxFileSize));
    } catch (NoSuchMethodError ex) {
        // Logback < 1.1.8 used String configuration
        Method method = ReflectionUtils.findMethod(
                SizeAndTimeBasedRollingPolicy.class, "setMaxFileSize", String.class);
        ReflectionUtils.invokeMethod(method, rollingPolicy, maxFileSize);
    }
}
 
Example #4
Source File: LogHelper.java    From gocd with Apache License 2.0 5 votes vote down vote up
public static void rollingPolicyForAppender(RollingFileAppender rollingFileAppender, String maxFileSize, String totalSizeCap, int maxHistory) {
    SizeAndTimeBasedRollingPolicy rollingPolicy = new SizeAndTimeBasedRollingPolicy();
    rollingPolicy.setContext(LOGGER_CONTEXT);
    rollingPolicy.setMaxHistory(maxHistory);
    rollingPolicy.setMaxFileSize(FileSize.valueOf(maxFileSize));
    rollingPolicy.setTotalSizeCap(FileSize.valueOf(totalSizeCap));
    rollingPolicy.setFileNamePattern(rollingFileAppender.rawFileProperty() + ".%d{yyyy-MM-dd}.%i.gz");
    rollingPolicy.setParent(rollingFileAppender);
    rollingFileAppender.setRollingPolicy(rollingPolicy);
    rollingPolicy.start();
}
 
Example #5
Source File: AionLoggerFactory.java    From aion with MIT License 4 votes vote down vote up
private static List<Appender<ILoggingEvent>> constructAppenders(
        boolean shouldLogToFile, String _logDirectory) {
    List<Appender<ILoggingEvent>> appenders = new ArrayList<>();

    String logDirectory = DEFAULT_LOG_DIR;
    if (_logDirectory != null && !_logDirectory.trim().isEmpty()) logDirectory = _logDirectory;

    PatternLayoutEncoder encoder = new PatternLayoutEncoder();
    encoder.setContext(context);
    encoder.setPattern(DEFAULT_LOG_PATTERN);
    encoder.start();

    ConsoleAppender<ILoggingEvent> consoleSync = new ConsoleAppender<>();
    consoleSync.setContext(context);
    consoleSync.setName("consoleSyncAppender"); // for logger debugging
    consoleSync.setEncoder(encoder);
    consoleSync.start();

    AsyncAppender consoleAsync = new AsyncAppender();
    consoleAsync.setContext(context);
    consoleAsync.setName("consoleAsyncAppender"); // for logger debugging
    consoleAsync.addAppender(consoleSync);

    consoleAsync.setIncludeCallerData(ASYNC_LOGGER_INCLUDE_CALLER_DATA);
    consoleAsync.setNeverBlock(ASYNC_LOGGER_NEVER_BLOCK);
    consoleAsync.setMaxFlushTime(ASYNC_LOGGER_MAX_FLUSH_TIME_MS);
    consoleAsync.setDiscardingThreshold(ASYNC_LOGGER_DISCARDING_THRESHOLD);
    consoleAsync.setQueueSize(ASYNC_LOGGER_QUEUE_SIZE);
    consoleAsync.start();

    appenders.add(consoleAsync);
    if (!shouldLogToFile) return appenders;

    RollingFileAppender<ILoggingEvent> fileSync = new RollingFileAppender<>();

    SizeBasedTriggeringPolicy<ILoggingEvent> tp = new SizeBasedTriggeringPolicy<>();
    tp.setContext(context);
    tp.start();

    SizeAndTimeBasedRollingPolicy rp = new SizeAndTimeBasedRollingPolicy();
    rp.setContext(context);
    // roll-over each day
    // notice that we don't use the OS-agnostic File.separator here since logback is converts
    // the FileNamePattern
    // to a unix-style path using ch.qos.logback.core.rolling.helper.FileFilterUtil.slashify
    FileNamePattern fnp =
            new FileNamePattern(
                    logDirectory + "/%d{yyyy/MM, aux}/aion.%d{yyyy-MM-dd}.%i.log", context);
    rp.setFileNamePattern(fnp.getPattern());
    // max rollover file size = 100MB
    rp.setMaxFileSize(FileSize.valueOf("100mb"));
    rp.setParent(fileSync);
    rp.start();

    fileSync.setName("fileSyncAppender"); // for logger debugging
    fileSync.setContext(context);
    fileSync.setTriggeringPolicy(tp);
    fileSync.setRollingPolicy(rp);
    fileSync.setFile(logDirectory + File.separator + DEFAULT_LOG_FILE_CURRENT);
    fileSync.setEncoder(encoder);
    fileSync.setAppend(true);
    fileSync.start();

    AsyncAppender fileAsync = new AsyncAppender();
    fileAsync.setContext(context);
    fileAsync.setName("fileAsyncAppender"); // for logger debugging
    fileAsync.addAppender(fileSync);

    fileAsync.setIncludeCallerData(ASYNC_LOGGER_INCLUDE_CALLER_DATA);
    fileAsync.setNeverBlock(ASYNC_LOGGER_NEVER_BLOCK);
    fileAsync.setMaxFlushTime(ASYNC_LOGGER_MAX_FLUSH_TIME_MS);
    fileAsync.setDiscardingThreshold(ASYNC_LOGGER_DISCARDING_THRESHOLD);
    fileAsync.setQueueSize(ASYNC_LOGGER_QUEUE_SIZE);
    fileAsync.start();

    appenders.add(fileAsync);
    return appenders;
}
 
Example #6
Source File: LogAppender.java    From nuls-v2 with MIT License 4 votes vote down vote up
/**
 * 通过传入的名字和级别,动态设置appender
 *
 * @param fileName
 * @return
 */
@SuppressWarnings("unchecked")
public static RollingFileAppender getAppender(String fileName, Level level){
    String rootPath = PROJECT_PATH;
    if(!rootPath.endsWith(File.separator)){
        rootPath += File.separator;
    }
    if(fileName.startsWith(File.separator)){
        fileName = fileName.substring(1);
    }
    LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
    RollingFileAppender appender = new RollingFileAppender();
    /*设置上下文,每个logger都关联到logger上下文,默认上下文名称为default。
    但可以使用<contextName>设置成其他名字,用于区分不同应用程序的记录。一旦设置,不能修改。*/
    appender.setContext(context);

    //这里设置级别过滤器
    LogFilter levelController = new LogFilter();
    ThresholdFilter levelFilter = levelController.getThresholdFilter(level);
    levelFilter.start();
    appender.addFilter(levelFilter);

    //设置文件名
    appender.setFile(OptionHelper.substVars(rootPath+fileName + ".log",context));
    appender.setAppend(true);
    appender.setPrudent(false);
    //设置文件创建时间及大小的类
    SizeAndTimeBasedRollingPolicy policy = new SizeAndTimeBasedRollingPolicy();
    //文件名格式
    String fp = OptionHelper.substVars(rootPath+ fileName + ".%d{yyyy-MM-dd}.%i.zip",context);
    //最大日志文件大小
    policy.setMaxFileSize(FileSize.valueOf("100MB"));
    //设置文件名模式
    policy.setFileNamePattern(fp);
    //设置保存最近3天的日志
    policy.setMaxHistory(3);
    //总大小限制
    policy.setContext(context);
    policy.setTotalSizeCap(FileSize.valueOf("1GB"));
    //设置父节点是appender
    policy.setParent(appender);
    //设置上下文,每个logger都关联到logger上下文,默认上下文名称为default。
    //但可以使用<contextName>设置成其他名字,用于区分不同应用程序的记录。一旦设置,不能修改。
    policy.start();
    PatternLayoutEncoder encoder = new PatternLayoutEncoder();
    //设置上下文,每个logger都关联到logger上下文,默认上下文名称为default。
    //但可以使用<contextName>设置成其他名字,用于区分不同应用程序的记录。一旦设置,不能修改。
    encoder.setContext(context);
    //设置格式
    /*encoder.setPattern("%d{yyyy-MM-dd HH:mm:ss.SSS} %5p [%t] %replace(%caller{1}){'\\t|Caller.{1}0|\\r\\n', ''} - %msg%n");*/
    encoder.setPattern("%d %p [%t] - %msg%n");
    encoder.start();
    //加入下面两个节点
    appender.setRollingPolicy(policy);
    appender.setEncoder(encoder);
    appender.start();
    return appender;
}
 
Example #7
Source File: LogbackUtil.java    From summerframework with Apache License 2.0 2 votes vote down vote up
public RollingFileAppender getAppender(String name, Level level, String fileName) {
    DateFormat format = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.SIMPLIFIED_CHINESE);
    LoggerContext context = (LoggerContext)LoggerFactory.getILoggerFactory();

    RollingFileAppender appender = new RollingFileAppender();

    LevelFilter levelFilter = getLevelFilter(level);
    levelFilter.start();
    appender.addFilter(levelFilter);

    appender.setContext(context);

    appender.setName(name);

    appender.setFile(OptionHelper.substVars("/opt/app/logs/" + fileName + ".json", context));

    appender.setAppend(true);

    appender.setPrudent(false);

    SizeAndTimeBasedRollingPolicy policy = new SizeAndTimeBasedRollingPolicy();

    String fp = OptionHelper.substVars(
        "/opt/app/logs/histroy" + fileName + format.format(new Date()) + "/.%d{yyyy-MM-dd}.%i.json", context);

    policy.setMaxFileSize(FileSize.valueOf("128MB"));

    policy.setFileNamePattern(fp);

    policy.setMaxHistory(7);

    policy.setTotalSizeCap(FileSize.valueOf("32GB"));

    policy.setParent(appender);

    policy.setContext(context);
    policy.start();

    PatternLayoutEncoder encoder = new PatternLayoutEncoder();

    encoder.setContext(context);

    encoder.setPattern("%d %p (%file:%line\\)- %m%n");
    encoder.start();

    appender.setRollingPolicy(policy);
    appender.setEncoder(encoder);
    appender.start();
    return appender;
}