Java Code Examples for ch.qos.logback.core.rolling.RollingFileAppender#setTriggeringPolicy()

The following examples show how to use ch.qos.logback.core.rolling.RollingFileAppender#setTriggeringPolicy() . 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: EnhancedLogbackConfiguration.java    From super-cloudops with Apache License 2.0 6 votes vote down vote up
private void setMaxFileSize(RollingFileAppender<ILoggingEvent> appender, LogbackConfigurator config) {
	SizeBasedTriggeringPolicy<ILoggingEvent> triggeringPolicy = new SizeBasedTriggeringPolicy<ILoggingEvent>();
	try {
		//
		// Start - for customized
		//
		String maxFileSize = this.logging.getProperty("policy.maxFileSize", "10MB");
		triggeringPolicy.setMaxFileSize(FileSize.valueOf(maxFileSize));
		// End - for customized

	} catch (NoSuchMethodError ex) {
		// Logback < 1.1.8 used String configuration
		Method method = ReflectionUtils.findMethod(SizeBasedTriggeringPolicy.class, "setMaxFileSize", String.class);
		ReflectionUtils.invokeMethod(method, triggeringPolicy, "10MB");
	}
	appender.setTriggeringPolicy(triggeringPolicy);
	config.start(triggeringPolicy);
}
 
Example 2
Source File: AppenderUtils.java    From singer with Apache License 2.0 5 votes vote down vote up
/**
 * Create the basic thrift appender which logs to a file
 * and rolls the file when it exceeds a certain size.
 *
 * @param basePath base directory the files are under.
 * @param topic the topic name for the current appender.
 * @param rotateThresholdKBytes threshold in kilobytes to rotate after.
 * @param context the logback context.
 */
public static Appender<LogMessage> createFileRollingThriftAppender(
    File basePath,
    String topic,
    long rotateThresholdKBytes,
    Context context,
    int maxRetentionHours) {
  RollingFileAppender<LogMessage> appender = new RollingFileAppender<LogMessage>();
  appender.setContext(context);
  appender.setAppend(true);
  appender.setPrudent(false);

  LogMessageEncoder encoder = new LogMessageEncoder();
  appender.setEncoder(encoder);
  appender.setFile(basePath + PATH_SEP + topic);

  TimeBasedRollingPolicy policy = new TimeBasedRollingPolicy();
  policy.setMaxHistory(maxRetentionHours);
  policy.setFileNamePattern(basePath + PATH_SEP + topic + ".%d{yyyy-MM-dd-HH}.%i");
  policy.setCleanHistoryOnStart(false);
  policy.setContext(context);
  policy.setParent(appender);

  // Also impose a max size per file policy.
  SizeAndTimeBasedFNATP fnatp = new SizeAndTimeBasedFNATP();
  fnatp.setContext(context);
  fnatp.setTimeBasedRollingPolicy(policy);
  fnatp.setMaxFileSize(FileSize.valueOf(String.format("%sKB", rotateThresholdKBytes)));

  policy.setTimeBasedFileNamingAndTriggeringPolicy(fnatp);
  appender.setRollingPolicy(policy);
  appender.setTriggeringPolicy(policy);

  policy.start();
  appender.start();

  return appender;
}
 
Example 3
Source File: BaleenFileLoggerBuilder.java    From baleen with Apache License 2.0 5 votes vote down vote up
/**
 * Create an appender that will roll over based on size
 *
 * @param context
 * @param encoder
 * @return An appender that matches the set up of the logger builder
 */
private RollingFileAppender<ILoggingEvent> createLogAppender(
    LoggerContext context, Encoder<ILoggingEvent> encoder) {
  RollingFileAppender<ILoggingEvent> appender = new RollingFileAppender<>();
  appender.setEncoder(encoder);
  appender.setFile(file);

  FixedWindowRollingPolicy rolling = new FixedWindowRollingPolicy();
  rolling.setParent(appender);
  rolling.setContext(context);

  // Set the maximum number of logs, either to the user specified setting or default to 1
  rolling.setMinIndex(1);
  if (maxNumberLogs.isPresent() && maxNumberLogs.get() >= 0) {
    rolling.setMaxIndex(maxNumberLogs.get());
  } else {
    rolling.setMaxIndex(1);
  }
  rolling.setFileNamePattern(getFileWithPattern("%i"));

  // Configure size based rolling
  SizeBasedTriggeringPolicy<ILoggingEvent> trigger = new SizeBasedTriggeringPolicy<>();
  trigger.setMaxFileSize(getMaxFileSize());
  trigger.setContext(context);

  rolling.start();
  trigger.start();
  appender.setRollingPolicy(rolling);
  appender.setTriggeringPolicy(trigger);

  return appender;
}
 
Example 4
Source File: LogbackConfiguration.java    From milkman with MIT License 4 votes vote down vote up
private void setupFileAppender(LoggerContext loggerContext) {
	RollingFileAppender<ILoggingEvent> fa = new RollingFileAppender<ILoggingEvent>();
	fa.setFile(PlatformUtil.getWritableLocationForFile("errors.log"));
	
	SizeBasedTriggeringPolicy<ILoggingEvent> sizePolicy = new SizeBasedTriggeringPolicy<ILoggingEvent>();
	sizePolicy.setContext(loggerContext);
	sizePolicy.setMaxFileSize(FileSize.valueOf("10mb"));
	sizePolicy.start();
	fa.setTriggeringPolicy(sizePolicy);
	var policy = new FixedWindowRollingPolicy();
	policy.setMaxIndex(3);
	policy.setMinIndex(1);
	policy.setFileNamePattern("errors.%i.log.zip");
	policy.setParent(fa);
	policy.setContext(loggerContext);
	policy.start();
	fa.setRollingPolicy(policy);
	
	
	fa.setContext(loggerContext);
	fa.setName("FILE");
	
	var filter = new ThresholdFilter();
	filter.setLevel("ERROR");
	filter.start();
	fa.addFilter(filter);

	LayoutWrappingEncoder<ILoggingEvent> encoder = new LayoutWrappingEncoder<ILoggingEvent>();
	encoder.setContext(loggerContext);

	// same as
	// PatternLayout layout = new PatternLayout();
	// layout.setPattern("%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n");
	PatternLayout layout = new PatternLayout();
	layout.setPattern("%date %level [%thread] %logger{10} [%file:%line] %msg%n");

	layout.setContext(loggerContext);
	layout.start();
	encoder.setLayout(layout);
	fa.setEncoder(encoder);

	
	fa.start();

	Logger rootLogger = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME);
	rootLogger.addAppender(fa);
}
 
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: AppenderUtils.java    From qpid-broker-j with Apache License 2.0 4 votes vote down vote up
public static void configureRollingFileAppender(FileLoggerSettings fileLoggerSettings,
                                                Context loggerContext,
                                                RollingFileAppender<ILoggingEvent> appender)
{
    String fileName = fileLoggerSettings.getFileName();
    File file = new File(fileName);
    if (file.getParentFile() != null)
    {
        file.getParentFile().mkdirs();
    }
    validateLogFilePermissions(file);
    validateMaxFileSize(fileLoggerSettings.getMaxFileSize());

    appender.setFile(fileName);
    appender.setAppend(true);
    appender.setContext(loggerContext);

    TriggeringPolicy triggeringPolicy;
    RollingPolicyBase rollingPolicy;
    final String maxFileSizeAsString = String.valueOf(fileLoggerSettings.getMaxFileSize()) + "MB";
    if(fileLoggerSettings.isRollDaily())
    {
        DailyTriggeringPolicy dailyTriggeringPolicy = new DailyTriggeringPolicy(fileLoggerSettings.isRollOnRestart(), maxFileSizeAsString);
        dailyTriggeringPolicy.setContext(loggerContext);
        TimeBasedRollingPolicy<ILoggingEvent> timeBasedRollingPolicy = new TimeBasedRollingPolicy<>();
        timeBasedRollingPolicy.setMaxHistory(fileLoggerSettings.getMaxHistory());
        timeBasedRollingPolicy.setTimeBasedFileNamingAndTriggeringPolicy(dailyTriggeringPolicy);
        timeBasedRollingPolicy.setFileNamePattern(fileName + ".%d{yyyy-MM-dd}.%i" + (fileLoggerSettings.isCompressOldFiles()
                ? ".gz"
                : ""));
        rollingPolicy = timeBasedRollingPolicy;
        triggeringPolicy = dailyTriggeringPolicy;
    }
    else
    {
        SizeTriggeringPolicy sizeTriggeringPolicy = new SizeTriggeringPolicy(fileLoggerSettings.isRollOnRestart(), maxFileSizeAsString);
        sizeTriggeringPolicy.setContext(loggerContext);
        SimpleRollingPolicy simpleRollingPolicy = new SimpleRollingPolicy(fileLoggerSettings.getMaxHistory());
        simpleRollingPolicy.setFileNamePattern(fileName + ".%i" + (fileLoggerSettings.isCompressOldFiles() ? ".gz" : ""));
        rollingPolicy = simpleRollingPolicy;
        triggeringPolicy = sizeTriggeringPolicy;
    }

    rollingPolicy.setContext(loggerContext);
    RollingPolicyDecorator decorator = new RollingPolicyDecorator(rollingPolicy, fileLoggerSettings.getRolloverListener(), fileLoggerSettings.getExecutorService());
    decorator.setParent(appender);
    appender.setRollingPolicy(decorator);
    appender.setTriggeringPolicy(triggeringPolicy);
    decorator.start();
    triggeringPolicy.start();

    final PatternLayoutEncoder encoder = new PatternLayoutEncoder();
    encoder.setPattern(fileLoggerSettings.getLayout());
    encoder.setContext(loggerContext);
    encoder.start();
    appender.setEncoder(encoder);
}
 
Example 7
Source File: Log.java    From bisq with GNU Affero General Public License v3.0 4 votes vote down vote up
public static void setup(String fileName) {
    LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();

    RollingFileAppender<ILoggingEvent> appender = new RollingFileAppender<>();
    appender.setContext(loggerContext);
    appender.setFile(fileName + ".log");

    FixedWindowRollingPolicy rollingPolicy = new FixedWindowRollingPolicy();
    rollingPolicy.setContext(loggerContext);
    rollingPolicy.setParent(appender);
    rollingPolicy.setFileNamePattern(fileName + "_%i.log");
    rollingPolicy.setMinIndex(1);
    rollingPolicy.setMaxIndex(10);
    rollingPolicy.start();

    SizeBasedTriggeringPolicy<ILoggingEvent> triggeringPolicy = new SizeBasedTriggeringPolicy<>();
    triggeringPolicy.setMaxFileSize(FileSize.valueOf("10MB"));
    triggeringPolicy.start();

    PatternLayoutEncoder encoder = new PatternLayoutEncoder();
    encoder.setContext(loggerContext);
    encoder.setPattern("%d{MMM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{15}: %msg %xEx%n");
    encoder.start();

    appender.setEncoder(encoder);
    appender.setRollingPolicy(rollingPolicy);
    appender.setTriggeringPolicy(triggeringPolicy);
    appender.start();

    logbackLogger = loggerContext.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
    logbackLogger.addAppender(appender);
    logbackLogger.setLevel(Level.INFO);

    // log errors in separate file
    // not working as expected still.... damn logback...
   /* FileAppender errorAppender = new FileAppender();
    errorAppender.setEncoder(encoder);
    errorAppender.setName("Error");
    errorAppender.setContext(loggerContext);
    errorAppender.setFile(fileName + "_error.log");
    LevelFilter levelFilter = new LevelFilter();
    levelFilter.setLevel(Level.ERROR);
    levelFilter.setOnMatch(FilterReply.ACCEPT);
    levelFilter.setOnMismatch(FilterReply.DENY);
    levelFilter.start();
    errorAppender.addFilter(levelFilter);
    errorAppender.start();
    logbackLogger.addAppender(errorAppender);*/
}
 
Example 8
Source File: FlickrUploader.java    From flickr-uploader with GNU General Public License v2.0 4 votes vote down vote up
private static void initLogs() {
    Logger logbackLogger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
    LoggerContext lc = logbackLogger.getLoggerContext();

    Logger rootLogger = lc.getLogger(Logger.ROOT_LOGGER_NAME);
    rootLogger.detachAndStopAllAppenders();

    TimeBasedRollingPolicy<ILoggingEvent> rollingPolicy = new TimeBasedRollingPolicy<ILoggingEvent>();
    rollingPolicy.setMaxHistory(3);
    SizeAndTimeBasedFNATP<ILoggingEvent> sizeAndTimeBasedFNATP = new SizeAndTimeBasedFNATP<ILoggingEvent>();
    sizeAndTimeBasedFNATP.setMaxFileSize("2MB");
    rollingPolicy.setTimeBasedFileNamingAndTriggeringPolicy(sizeAndTimeBasedFNATP);
    rollingPolicy.setFileNamePattern(context.getFilesDir().getPath() + "/logs/old/flickruploader.%d{yyyy-MM-dd}.%i.log");
    rollingPolicy.setContext(lc);

    RollingFileAppender<ILoggingEvent> fileAppender = new RollingFileAppender<ILoggingEvent>();
    fileAppender.setContext(lc);
    fileAppender.setFile(getLogFilePath());
    fileAppender.setRollingPolicy(rollingPolicy);
    fileAppender.setTriggeringPolicy(rollingPolicy);
    rollingPolicy.setParent(fileAppender);

    PatternLayoutEncoder pl = new PatternLayoutEncoder();
    pl.setContext(lc);
    pl.setCharset(Charset.defaultCharset());
    pl.setPattern("%d{HH:mm:ss.SSS} [%thread] %-5level %class{0}.%method:%L > %msg%n");
    pl.setImmediateFlush(false);
    pl.start();

    fileAppender.setEncoder(pl);
    fileAppender.setName("file");

    rollingPolicy.start();
    fileAppender.start();

    if (Config.isDebug()) {
        final PatternLayoutEncoder logcatTagPattern = new PatternLayoutEncoder();
        logcatTagPattern.setContext(lc);
        logcatTagPattern.setPattern("%class{0}");
        logcatTagPattern.start();

        final PatternLayoutEncoder logcatPattern = new PatternLayoutEncoder();
        logcatPattern.setContext(lc);
        logcatPattern.setPattern("[%thread] %method:%L > %msg%n");
        logcatPattern.start();

        final LogcatAppender logcatAppender = new LogcatAppender();
        logcatAppender.setContext(lc);
        logcatAppender.setTagEncoder(logcatTagPattern);
        logcatAppender.setEncoder(logcatPattern);
        logcatAppender.start();

        rootLogger.addAppender(logcatAppender);
    }

    rootLogger.addAppender(fileAppender);

}