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

The following examples show how to use ch.qos.logback.core.rolling.RollingFileAppender. 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: Minister.java    From GOAi with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 初始化日志
 */
private Logger initLog(Integer id) {
    // 实例化log,每个实例存放地方不一致
    ch.qos.logback.classic.Logger logger = ((ch.qos.logback.classic.Logger)
            LoggerFactory.getLogger(this.secretary.strategyName + "-" + id));

    LoggerContext context = logger.getLoggerContext();

    TimeBasedRollingPolicy<ILoggingEvent> policy = new TimeBasedRollingPolicy<>();
    policy.setFileNamePattern(OptionHelper.substVars(
            "logs/past/" + id + "/%d{yyyy-MM-dd}.log.gz", context));
    policy.setMaxHistory(31);
    policy.setContext(context);

    PatternLayoutEncoder encoder = new PatternLayoutEncoder();
    encoder.setContext(context);
    encoder.setPattern("%d{yyyy-MM-dd HH:mm:ss.SSS} %5level - [%thread] %logger : %msg%n");

    RollingFileAppender<ILoggingEvent> appender = new RollingFileAppender<>();
    appender.setContext(context);
    appender.setName(this.secretary.strategyName + "-" + id);
    appender.setFile(OptionHelper.substVars("logs/" + id + "/log.log", context));
    appender.setAppend(true);
    // 同一文件多输入完整检查
    appender.setPrudent(false);
    appender.setRollingPolicy(policy);
    appender.setEncoder(encoder);
    policy.setParent(appender);

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

    logger.setLevel(Level.INFO);
    // 终端输出
    logger.setAdditive(true);
    logger.addAppender(appender);

    return logger;
}
 
Example #2
Source File: DynamicLogback918Logger.java    From tddl5 with Apache License 2.0 6 votes vote down vote up
protected Appender buildDailyMaxRollingAppender(String name, String fileName, String pattern, int maxBackupIndex) {
    RollingFileAppender appender = new RollingFileAppender();
    appender.setContext(loggerContext);
    appender.setName(name);
    appender.setAppend(true);
    appender.setFile(new File(getLogPath(), fileName).getAbsolutePath());

    TimeBasedRollingPolicy rolling = new TimeBasedRollingPolicy();
    rolling.setContext(loggerContext);
    rolling.setFileNamePattern(new File(getLogPath(), fileName).getAbsolutePath() + ".%d{yyyy-MM-dd-HH}");
    rolling.setMaxHistory(maxBackupIndex);
    rolling.setParent(appender);
    rolling.start();
    appender.setRollingPolicy(rolling);

    PatternLayout layout = new PatternLayout();
    layout.setContext(loggerContext);
    layout.setPattern(pattern);
    layout.start();
    appender.setLayout(layout);
    // 启动
    appender.start();
    return appender;
}
 
Example #3
Source File: DynamicLogback918Logger.java    From tddl5 with Apache License 2.0 6 votes vote down vote up
protected Appender buildAppender(String name, String fileName, String pattern) {
    RollingFileAppender appender = new RollingFileAppender();
    appender.setContext(loggerContext);
    appender.setName(name);
    appender.setAppend(true);
    appender.setFile(new File(getLogPath(), fileName).getAbsolutePath());

    TimeBasedRollingPolicy rolling = new TimeBasedRollingPolicy();
    rolling.setParent(appender);
    rolling.setFileNamePattern(new File(getLogPath(), fileName).getAbsolutePath() + ".%d{yyyy-MM-dd}");
    rolling.setContext(loggerContext);
    rolling.start();
    appender.setRollingPolicy(rolling);

    PatternLayout layout = new PatternLayout();
    layout.setPattern(pattern);
    layout.setContext(loggerContext);
    layout.start();
    appender.setLayout(layout);
    // 启动
    appender.start();
    return appender;
}
 
Example #4
Source File: DynamicLogbackLogger.java    From tddl5 with Apache License 2.0 6 votes vote down vote up
protected Appender buildDailyMaxRollingAppender(String name, String fileName, String pattern, int maxBackupIndex) {
    RollingFileAppender appender = new RollingFileAppender();
    appender.setContext(loggerContext);
    appender.setName(name);
    appender.setAppend(true);
    appender.setFile(new File(getLogPath(), fileName).getAbsolutePath());

    TimeBasedRollingPolicy rolling = new TimeBasedRollingPolicy();
    rolling.setContext(loggerContext);
    rolling.setFileNamePattern(new File(getLogPath(), fileName).getAbsolutePath() + ".%d{yyyy-MM-dd-HH}");
    rolling.setMaxHistory(maxBackupIndex);
    rolling.setParent(appender);
    rolling.start();
    appender.setRollingPolicy(rolling);

    PatternLayoutEncoder layout = new PatternLayoutEncoder();
    layout.setContext(loggerContext);
    layout.setPattern(pattern);
    layout.setCharset(Charset.forName(getEncoding()));
    layout.start();
    appender.setEncoder(layout);
    // 启动
    appender.start();
    return appender;
}
 
Example #5
Source File: DynamicLogbackLogger.java    From tddl5 with Apache License 2.0 6 votes vote down vote up
protected Appender buildAppender(String name, String fileName, String pattern) {
    RollingFileAppender appender = new RollingFileAppender();
    appender.setContext(loggerContext);
    appender.setName(name);
    appender.setAppend(true);
    appender.setFile(new File(getLogPath(), fileName).getAbsolutePath());

    TimeBasedRollingPolicy rolling = new TimeBasedRollingPolicy();
    rolling.setContext(loggerContext);
    rolling.setParent(appender);
    rolling.setFileNamePattern(new File(getLogPath(), fileName).getAbsolutePath() + ".%d{yyyy-MM-dd}");
    rolling.start();
    appender.setRollingPolicy(rolling);

    PatternLayoutEncoder layout = new PatternLayoutEncoder();
    layout.setContext(loggerContext);
    layout.setPattern(pattern);
    layout.setCharset(Charset.forName(getEncoding()));
    layout.start();
    appender.setEncoder(layout);
    // 启动
    appender.start();
    return appender;
}
 
Example #6
Source File: BrokerFileLoggerImpl.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
@Override
protected Appender<ILoggingEvent> createAppenderInstance(Context loggerContext)
{
    SystemConfig<?> systemConfig = getAncestor(SystemConfig.class);
    _logbackStatusListener = new BrokerLoggerStatusListener(this,
                                                            systemConfig,
                                                            BROKER_FAIL_ON_LOGGER_IO_ERROR,
                                                            IOException.class,
                                                            IOError.class);
    _statusManager = loggerContext.getStatusManager();
    _statusManager.add(_logbackStatusListener);

    final RollingFileAppender<ILoggingEvent> appender = new RollingFileAppender<>();
    AppenderUtils.configureRollingFileAppender(this, loggerContext, appender);
    return appender;
}
 
Example #7
Source File: DynamicLogbackLogger.java    From tddl with Apache License 2.0 6 votes vote down vote up
private Appender buildAppender(String name, String fileName, String pattern) {
    RollingFileAppender appender = new RollingFileAppender();
    appender.setName(name);
    appender.setAppend(true);
    appender.setFile(new File(getLogPath(), fileName).getAbsolutePath());

    TimeBasedRollingPolicy rolling = new TimeBasedRollingPolicy();
    rolling.setParent(appender);
    rolling.setFileNamePattern(new File(getLogPath(), fileName).getAbsolutePath() + ".%d{yyyy-MM-dd}");
    appender.setRollingPolicy(rolling);

    PatternLayoutEncoder layout = new PatternLayoutEncoder();
    layout.setPattern(pattern);
    layout.setCharset(Charset.forName(getEncoding()));
    appender.setEncoder(layout);
    // 启动
    appender.start();
    return appender;
}
 
Example #8
Source File: DynamicLogbackLogger.java    From tddl with Apache License 2.0 6 votes vote down vote up
private Appender buildDailyMaxRollingAppender(String name, String fileName, String pattern, int maxBackupIndex) {
    RollingFileAppender appender = new RollingFileAppender();
    appender.setName(name);
    appender.setAppend(true);
    appender.setFile(new File(getLogPath(), fileName).getAbsolutePath());

    TimeBasedRollingPolicy rolling = new TimeBasedRollingPolicy();
    rolling.setFileNamePattern(new File(getLogPath(), fileName).getAbsolutePath() + ".%d{yyyy-MM-dd-HH}");
    rolling.setMaxHistory(maxBackupIndex);
    rolling.setParent(appender);
    appender.setRollingPolicy(rolling);

    PatternLayoutEncoder layout = new PatternLayoutEncoder();
    layout.setPattern(pattern);
    layout.setCharset(Charset.forName(getEncoding()));
    appender.setEncoder(layout);
    // 启动
    appender.start();
    return appender;
}
 
Example #9
Source File: LogbackLogManager.java    From seed with Mozilla Public License 2.0 6 votes vote down vote up
private void configureFile(LoggingConfig.FileConfig fileConfig, Logger rootLogger) {
    if (fileConfig.isEnabled()) {
        FileAppender<ILoggingEvent> appender;
        TimeBasedRollingPolicy rollingPolicy = buildRollingPolicy(fileConfig);
        if (rollingPolicy != null) {
            appender = new RollingFileAppender<>();
            ((RollingFileAppender) appender).setRollingPolicy(rollingPolicy);
        } else {
            appender = new FileAppender<>();
        }
        appender.setContext(context);
        appender.setFile(fileConfig.getPath());
        appender.setEncoder(buildEncoder(fileConfig, DEFAULT_FILE_PATTERN));
        appender.start();
        rootLogger.addAppender(appender);
    }
}
 
Example #10
Source File: LogUtils.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Attaches archived log files to a given rolling file appender.
 * 
 * @param appender
 *            Logback rollingFileAppender
 * @param rollingFileAppenderResource
 *            Resource which should have attached archived log files.
 * @param logService
 *            Log service which should be use to retrieve archived log
 *            files.
 */
public static void attachArchivedLogFiles(
		RollingFileAppender<ILoggingEvent> appender,
		RollingFileAppenderResource rollingFileAppenderResource,
		ILogService logService) {

	File[] files = logService.getArchivedLogFiles(appender);
	if (files == null)
		return;

	List<ArchivedLogFileResource> logFiles = new ArrayList<ArchivedLogFileResource>(
			files.length);

	for (File file : files) {
		ArchivedLogFileResource resource = new ArchivedLogFileResource(
				rollingFileAppenderResource, file);
		logFiles.add(resource);
	}

	rollingFileAppenderResource.setArchivedLogFiles(logFiles);
}
 
Example #11
Source File: LogService.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public List<RollingFileAppender<ILoggingEvent>> getRollingFileAppenders() {
	List<RollingFileAppender<ILoggingEvent>> rollingFileAppenders = new LinkedList<RollingFileAppender<ILoggingEvent>>();

	for (Logger logger : getLoggers()) {
		for (Iterator<Appender<ILoggingEvent>> index = logger
				.iteratorForAppenders(); index.hasNext();) {

			Appender<ILoggingEvent> appender = index.next();
			if (appender instanceof RollingFileAppender)
				rollingFileAppenders
						.add((RollingFileAppender<ILoggingEvent>) appender);
		}
	}

	return rollingFileAppenders;
}
 
Example #12
Source File: LogService.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public File getArchivedLogFile(
		RollingFileAppender<ILoggingEvent> rollingFileAppender,
		String logFileName) {
	if (rollingFileAppender == null || logFileName == null)
		return null;

	File[] archvieLogFiles = getArchivedLogFiles(rollingFileAppender);
	if (archvieLogFiles == null)
		return null;

	for (File logFile : archvieLogFiles)
		if (logFileName.equals(logFile.getName()))
			return logFile;

	return null;
}
 
Example #13
Source File: DefaultPluginLoggingService.java    From gocd with Apache License 2.0 6 votes vote down vote up
private FileAppender<ILoggingEvent> getAppender(String pluginId) {
    File pluginLogFileLocation = pluginLogFile(pluginId);

    RollingFileAppender<ILoggingEvent> rollingFileAppender = new RollingFileAppender<>();
    rollingFileAppender.setEncoder(LogHelper.encoder());
    rollingFileAppender.setContext(LogHelper.LOGGER_CONTEXT);
    rollingFileAppender.setFile(pluginLogFileLocation.getPath());
    rollingFileAppender.setName(rollingFileAppenderName(pluginId));

    LogHelper.rollingPolicyForAppender(
            rollingFileAppender,
            "5 MB",
            "20 MB",
            7
    );

    rollingFileAppender.start();
    return rollingFileAppender;
}
 
Example #14
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 #15
Source File: EnhancedLogbackConfiguration.java    From super-cloudops with Apache License 2.0 6 votes vote down vote up
private void setRollingPolicy(RollingFileAppender<ILoggingEvent> appender, LogbackConfigurator config, String logFile) {
	FixedWindowRollingPolicy rollingPolicy = new FixedWindowRollingPolicy();
	//
	// Start - for customized
	//
	int minIndex = Integer.parseInt(logging.getProperty("policy.minIndex", "1"));
	int maxIndex = Integer.parseInt(logging.getProperty("policy.maxIndex", "7"));
	rollingPolicy.setMinIndex(minIndex);
	rollingPolicy.setMaxIndex(maxIndex);
	// End - for customized

	rollingPolicy.setFileNamePattern(logFile + ".%i");
	appender.setRollingPolicy(rollingPolicy);
	rollingPolicy.setParent(appender);
	config.start(rollingPolicy);
}
 
Example #16
Source File: AgentOutputAppender.java    From gocd with Apache License 2.0 6 votes vote down vote up
private RollingFileAppender<ILoggingEvent> rollingAppender(String file) {
    RollingFileAppender<ILoggingEvent> rollingFileAppender = new RollingFileAppender<>();
    rollingFileAppender.setEncoder(LogHelper.encoder("%date{ISO8601} - %msg%n"));
    rollingFileAppender.setContext(LogHelper.LOGGER_CONTEXT);
    rollingFileAppender.setFile(getEffectiveLogDirectory(file));
    rollingFileAppender.setName(UUID.randomUUID().toString());

    LogHelper.rollingPolicyForAppender(
            rollingFileAppender,
            "5 MB",
            "20 MB",
            4
    );
    rollingFileAppender.start();
    return rollingFileAppender;
}
 
Example #17
Source File: LogbackUtil.java    From summerframework with Apache License 2.0 6 votes vote down vote up
private static Logger build(String name, Level logLevel, String fileName) {
    LoggerContext context = (LoggerContext)LoggerFactory.getILoggerFactory();
    Logger logger = context.getLogger(name);
    if (Level.ALL.equals(logLevel)) {
        RollingFileAppender errorAppender = new AppenderBuild().getAppender(name, Level.ERROR, fileName);
        RollingFileAppender infoAppender = new AppenderBuild().getAppender(name, Level.INFO, fileName);
        RollingFileAppender warnAppender = new AppenderBuild().getAppender(name, Level.WARN, fileName);
        RollingFileAppender debugAppender = new AppenderBuild().getAppender(name, Level.DEBUG, fileName);

        logger.setAdditive(false);
        logger.addAppender(errorAppender);
        logger.addAppender(infoAppender);
        logger.addAppender(warnAppender);
        logger.addAppender(debugAppender);

    } else {
        logger = buildInfoByLevel(name, logLevel, fileName);
    }
    return logger;
}
 
Example #18
Source File: LogbackContainer.java    From dubbox with Apache License 2.0 5 votes vote down vote up
/**
 * Initializer logback
 * 
 * @param file
 * @param level
 * @param maxHistory
 */
private void doInitializer(String file, String level, int maxHistory) {
	LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
	Logger rootLogger = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME);
	rootLogger.detachAndStopAllAppenders();

	// appender
	RollingFileAppender<ILoggingEvent> fileAppender = new RollingFileAppender<ILoggingEvent>();
	fileAppender.setContext(loggerContext);
	fileAppender.setName("application");
	fileAppender.setFile(file);
	fileAppender.setAppend(true);

	// policy
	TimeBasedRollingPolicy<ILoggingEvent> policy = new TimeBasedRollingPolicy<ILoggingEvent>();
	policy.setContext(loggerContext);
	policy.setMaxHistory(maxHistory);
	policy.setFileNamePattern(file + ".%d{yyyy-MM-dd}");
	policy.setParent(fileAppender);
	policy.start();
	fileAppender.setRollingPolicy(policy);

	// encoder
	PatternLayoutEncoder encoder = new PatternLayoutEncoder();
	encoder.setContext(loggerContext);
	encoder.setPattern("%date [%thread] %-5level %logger (%file:%line\\) - %msg%n");
	encoder.start();
	fileAppender.setEncoder(encoder);
	
	fileAppender.start();

	rootLogger.addAppender(fileAppender);
	rootLogger.setLevel(Level.toLevel(level));
	rootLogger.setAdditive(false);
}
 
Example #19
Source File: LoggerBuilder.java    From nuls-v2 with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
private static NulsLogger build(String fileName, Level fileLevel, Level consoleLevel) {
    RollingFileAppender fileAppender = LogAppender.getAppender(fileName, fileLevel);
    LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
    Logger logger = context.getLogger(fileAppender.getEncoder().toString());
    //设置不向上级打印信息
    logger.setAdditive(false);
    logger.addAppender(fileAppender);
    //输出到控制台
    Appender consoleAppender = LogAppender.createConsoleAppender(consoleLevel);
    logger.addAppender(consoleAppender);
    return new NulsLogger(logger);
}
 
Example #20
Source File: LogbackContainer.java    From dubbo-2.6.5 with Apache License 2.0 5 votes vote down vote up
/**
 * Initializer logback
 *
 * @param file
 * @param level
 * @param maxHistory
 */
private void doInitializer(String file, String level, int maxHistory) {
    LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
    Logger rootLogger = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME);
    rootLogger.detachAndStopAllAppenders();

    // appender
    RollingFileAppender<ILoggingEvent> fileAppender = new RollingFileAppender<ILoggingEvent>();
    fileAppender.setContext(loggerContext);
    fileAppender.setName("application");
    fileAppender.setFile(file);
    fileAppender.setAppend(true);

    // policy
    TimeBasedRollingPolicy<ILoggingEvent> policy = new TimeBasedRollingPolicy<ILoggingEvent>();
    policy.setContext(loggerContext);
    policy.setMaxHistory(maxHistory);
    policy.setFileNamePattern(file + ".%d{yyyy-MM-dd}");
    policy.setParent(fileAppender);
    policy.start();
    fileAppender.setRollingPolicy(policy);

    // encoder
    PatternLayoutEncoder encoder = new PatternLayoutEncoder();
    encoder.setContext(loggerContext);
    encoder.setPattern("%date [%thread] %-5level %logger (%file:%line\\) - %msg%n");
    encoder.start();
    fileAppender.setEncoder(encoder);

    fileAppender.start();

    rootLogger.addAppender(fileAppender);
    rootLogger.setLevel(Level.toLevel(level));
    rootLogger.setAdditive(false);
}
 
Example #21
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 #22
Source File: SpacedLogbackSystem.java    From spring-cloud-formula with Apache License 2.0 5 votes vote down vote up
protected Appender<ILoggingEvent> fileAppender(Space space) {
    RollingFileAppender<ILoggingEvent> appender = new RollingFileAppender<>();
    PatternLayoutEncoder encoder = new PatternLayoutEncoder();
    String logPattern = this.patterns.getProperty("logging.pattern.file", FILE_LOG_PATTERN);
    encoder.setPattern(OptionHelper.substVars(logPattern, context));
    encoder.setCharset(DEFAULT_CHARSET);
    appender.setEncoder(encoder);
    start(encoder);

    // parse path and file
    // first consider spec.path, second, default_spec.path, third logging.path
    LogFile logFile = LogFile.get(patterns);
    Properties defaultProperties = new Properties();
    if (logFile != null) {
        logFile.applyTo(defaultProperties);
    }
    String path = space.getSpec().getPath() != null ? space.getSpec().getPath() :
            space.getDefaultSpec().getPath() != null ? space.getDefaultSpec().getPath() :
                    defaultProperties.contains(LoggingSystemProperties.LOG_PATH)
                            ? defaultProperties.getProperty(LoggingSystemProperties.LOG_PATH) :
                            DEFAULT_PATH;
    path = patterns.resolvePlaceholders(path);
    String file = space.getSpec().getFile() != null
            ? fileName(space.getSpec().getFile()) : fileName(space.getName());
    file = patterns.resolvePlaceholders(file);
    appender.setFile(path + "/" + file);
    setRollingPolicy(appender, space, path, file);

    //  threshold config
    ThresholdFilter thresholdFilter = new ThresholdFilter();
    if (space.getSpec().getThreshold() != null) {
        thresholdFilter.setLevel(space.getSpec().getThreshold());
        start(thresholdFilter);
        appender.addFilter(thresholdFilter);
    }

    appender("SPACE-" + space.getName(), appender);
    return appender;
}
 
Example #23
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 #24
Source File: BaleenFileLoggerBuilder.java    From baleen with Apache License 2.0 5 votes vote down vote up
/**
 * Create an appender that will create a new log each day
 *
 * @param context
 * @param encoder
 * @return An appender that matches the set up of the logger builder
 */
private RollingFileAppender<ILoggingEvent> createDailyLogAppender(
    LoggerContext context, Encoder<ILoggingEvent> encoder) {
  RollingFileAppender<ILoggingEvent> appender = new RollingFileAppender<>();
  appender.setEncoder(encoder);
  appender.setFile(file);

  TimeBasedRollingPolicy<ILoggingEvent> rolling = new TimeBasedRollingPolicy<>();
  rolling.setContext(context);
  rolling.setParent(appender);

  rolling.setFileNamePattern(getFileWithPattern("%d"));

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

  // Do we need to also split files by size?
  if (divideBasedOnSize()) {
    SizeAndTimeBasedFNATP<ILoggingEvent> sizeBased = new SizeAndTimeBasedFNATP<>();
    sizeBased.setContext(context);
    sizeBased.setMaxFileSize(getMaxFileSize());
    sizeBased.setTimeBasedRollingPolicy(rolling);

    rolling.setTimeBasedFileNamingAndTriggeringPolicy(sizeBased);
  }

  rolling.start();
  if (rolling.getTimeBasedFileNamingAndTriggeringPolicy() != null) {
    rolling.getTimeBasedFileNamingAndTriggeringPolicy().start();
  }
  appender.setRollingPolicy(rolling);

  return appender;
}
 
Example #25
Source File: LogbackContainer.java    From dubbox with Apache License 2.0 5 votes vote down vote up
/**
 * Initializer logback
 * 
 * @param file
 * @param level
 * @param maxHistory
 */
private void doInitializer(String file, String level, int maxHistory) {
	LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
	Logger rootLogger = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME);
	rootLogger.detachAndStopAllAppenders();

	// appender
	RollingFileAppender<ILoggingEvent> fileAppender = new RollingFileAppender<ILoggingEvent>();
	fileAppender.setContext(loggerContext);
	fileAppender.setName("application");
	fileAppender.setFile(file);
	fileAppender.setAppend(true);

	// policy
	TimeBasedRollingPolicy<ILoggingEvent> policy = new TimeBasedRollingPolicy<ILoggingEvent>();
	policy.setContext(loggerContext);
	policy.setMaxHistory(maxHistory);
	policy.setFileNamePattern(file + ".%d{yyyy-MM-dd}");
	policy.setParent(fileAppender);
	policy.start();
	fileAppender.setRollingPolicy(policy);

	// encoder
	PatternLayoutEncoder encoder = new PatternLayoutEncoder();
	encoder.setContext(loggerContext);
	encoder.setPattern("%date [%thread] %-5level %logger (%file:%line\\) - %msg%n");
	encoder.start();
	fileAppender.setEncoder(encoder);
	
	fileAppender.start();

	rootLogger.addAppender(fileAppender);
	rootLogger.setLevel(Level.toLevel(level));
	rootLogger.setAdditive(false);
}
 
Example #26
Source File: LogbackContainer.java    From dubbo3 with Apache License 2.0 5 votes vote down vote up
/**
 * Initializer logback
 *
 * @param file       log file
 * @param level      log level
 * @param maxHistory max history
 */
private void doInitializer(String file, String level, int maxHistory) {
    LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
    Logger rootLogger = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME);
    rootLogger.detachAndStopAllAppenders();

    // appender
    RollingFileAppender<ILoggingEvent> fileAppender = new RollingFileAppender<>();
    fileAppender.setContext(loggerContext);
    fileAppender.setName("application");
    fileAppender.setFile(file);
    fileAppender.setAppend(true);

    // policy
    TimeBasedRollingPolicy<ILoggingEvent> policy = new TimeBasedRollingPolicy<>();
    policy.setContext(loggerContext);
    policy.setMaxHistory(maxHistory);
    policy.setFileNamePattern(file + ".%d{yyyy-MM-dd}");
    policy.setParent(fileAppender);
    policy.start();
    fileAppender.setRollingPolicy(policy);

    // encoder
    PatternLayoutEncoder encoder = new PatternLayoutEncoder();
    encoder.setContext(loggerContext);
    encoder.setPattern("%date [%thread] %-5level %logger (%file:%line\\) - %msg%n");
    encoder.start();
    fileAppender.setEncoder(encoder);

    fileAppender.start();

    rootLogger.addAppender(fileAppender);
    rootLogger.setLevel(Level.toLevel(level));
    rootLogger.setAdditive(false);
}
 
Example #27
Source File: MultipleFileLogReader.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void setAppender(Appender<?> appender) {
	super.setAppender(appender);
	if (appender instanceof RollingFileAppender) {
		RollingPolicy rp = ((RollingFileAppender<?>) appender).getRollingPolicy();
		if (rp instanceof TimeBasedRollingPolicy) {
			fileNamePattern = ((TimeBasedRollingPolicy) rp).getFileNamePattern();
		} else {
			throw new UnsupportedOperationException("Must be TimeBasedRollingPolicy!");
		}
	} else {
		throw new RuntimeException("MultipleFileLogReader appender must be an instance of RollingFileAppender!");
	}
}
 
Example #28
Source File: AppenderUtilsTest.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateRollingFileAppenderNonDailyRolling()
{
    when(_settings.isRollDaily()).thenReturn(Boolean.FALSE);
    when(_settings.isCompressOldFiles()).thenReturn(Boolean.FALSE);

    RollingFileAppender<ILoggingEvent> appender = new RollingFileAppender<>();
    AppenderUtils.configureRollingFileAppender(_settings, new LoggerContext(), appender);

    assertEquals("Unexpected appender file name", _testLogFileName, appender.getFile());

    RollingPolicy rollingPolicy = appender.getRollingPolicy();
    final boolean condition2 = rollingPolicy instanceof RollingPolicyDecorator;
    assertTrue("Unexpected rolling policy", condition2);
    rollingPolicy = ((RollingPolicyDecorator)rollingPolicy).getDecorated();
    final boolean condition1 = rollingPolicy instanceof AppenderUtils.SimpleRollingPolicy;
    assertTrue("Unexpected decorated rolling policy", condition1);
    assertEquals("Unexpected max history",
                        (long) MAX_HISTORY,
                        (long) ((AppenderUtils.SimpleRollingPolicy) rollingPolicy).getMaxIndex());
    assertEquals("Unexpected file name pattern",
                        _testLogFileName + ".%i",
                        ((AppenderUtils.SimpleRollingPolicy) rollingPolicy).getFileNamePattern());
    assertEquals("Unexpected compression mode", CompressionMode.NONE, rollingPolicy.getCompressionMode());

    TriggeringPolicy triggeringPolicy = appender.getTriggeringPolicy();
    assertEquals("Unexpected triggering policy",
                        String.valueOf(MAX_FILE_SIZE) + " MB",
                        ((AppenderUtils.SizeTriggeringPolicy) triggeringPolicy).getMaxFileSize().toString());

    Encoder encoder = appender.getEncoder();
    final boolean condition = encoder instanceof PatternLayoutEncoder;
    assertTrue("Unexpected encoder", condition);
    assertEquals("Unexpected layout pattern", LAYOUT, ((PatternLayoutEncoder)encoder).getPattern());
}
 
Example #29
Source File: AppenderUtilsTest.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateRollingFileAppenderDailyRolling()
{
    final RollingFileAppender<ILoggingEvent> appender = new RollingFileAppender<>();
    AppenderUtils.configureRollingFileAppender(_settings, new LoggerContext(), appender);

    assertEquals("Unexpected appender file name", _testLogFileName, appender.getFile());

    RollingPolicy rollingPolicy = appender.getRollingPolicy();
    final boolean condition2 = rollingPolicy instanceof RollingPolicyDecorator;
    assertTrue("Unexpected rolling policy", condition2);
    rollingPolicy = ((RollingPolicyDecorator)rollingPolicy).getDecorated();
    final boolean condition1 = rollingPolicy instanceof TimeBasedRollingPolicy;
    assertTrue("Unexpected decorated rolling policy", condition1);
    assertEquals("Unexpected max history",
                        (long) MAX_HISTORY,
                        (long) ((TimeBasedRollingPolicy) rollingPolicy).getMaxHistory());

    assertEquals("Unexpected file name pattern",
                        _testLogFileName + ".%d{yyyy-MM-dd}.%i.gz",
                        ((TimeBasedRollingPolicy) rollingPolicy).getFileNamePattern());

    assertEquals("Unexpected compression mode", CompressionMode.GZ, rollingPolicy.getCompressionMode());

    TriggeringPolicy triggeringPolicy = ((TimeBasedRollingPolicy) rollingPolicy).getTimeBasedFileNamingAndTriggeringPolicy();
    final boolean condition = triggeringPolicy instanceof AppenderUtils.DailyTriggeringPolicy;
    assertTrue("Unexpected triggering policy", condition);
    assertEquals("Unexpected triggering policy",
                        String.valueOf(MAX_FILE_SIZE) + " MB",
                        ((AppenderUtils.DailyTriggeringPolicy) triggeringPolicy).getMaxFileSize().toString());
    assertEquals("Unexpected layout", LAYOUT, ((PatternLayoutEncoder) appender.getEncoder()).getPattern());
}
 
Example #30
Source File: VirtualHostFileLoggerImpl.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@Override
protected Appender<ILoggingEvent> createAppenderInstance(Context loggerContext)
{
    final RollingFileAppender<ILoggingEvent> appender = new RollingFileAppender<>();
    AppenderUtils.configureRollingFileAppender(this, loggerContext, appender);
    return appender;
}