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

The following examples show how to use ch.qos.logback.core.rolling.RollingFileAppender#setEncoder() . 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: 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 3
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 4
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 5
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 6
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 7
Source File: LogbackContainer.java    From dubbox-hystrix 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 8
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 9
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 10
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 11
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 12
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 13
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 14
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);

}
 
Example 15
Source File: BitherApplication.java    From bither-android with Apache License 2.0 4 votes vote down vote up
private void initLogging() {
    final File logDir = getLogDir();
    final File logFile = new File(logDir, "bitherj.log");
    final LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
    final PatternLayoutEncoder filePattern = new PatternLayoutEncoder();
    filePattern.setContext(context);
    filePattern.setPattern("%d{HH:mm:ss.SSS} [%thread] %logger{0} - %msg%n");
    filePattern.start();

    final RollingFileAppender<ILoggingEvent> fileAppender = new
            RollingFileAppender<ILoggingEvent>();
    fileAppender.setContext(context);
    fileAppender.setFile(logFile.getAbsolutePath());

    final TimeBasedRollingPolicy<ILoggingEvent> rollingPolicy = new
            TimeBasedRollingPolicy<ILoggingEvent>();
    rollingPolicy.setContext(context);
    rollingPolicy.setParent(fileAppender);
    rollingPolicy.setFileNamePattern(logDir.getAbsolutePath() + "/bitherj.%d.log.gz");
    rollingPolicy.setMaxHistory(7);
    rollingPolicy.start();

    fileAppender.setEncoder(filePattern);
    fileAppender.setRollingPolicy(rollingPolicy);
    fileAppender.start();

    final PatternLayoutEncoder logcatTagPattern = new PatternLayoutEncoder();
    logcatTagPattern.setContext(context);
    logcatTagPattern.setPattern("%logger{0}");
    logcatTagPattern.start();

    final PatternLayoutEncoder logcatPattern = new PatternLayoutEncoder();
    logcatPattern.setContext(context);
    logcatPattern.setPattern("[%thread] %msg%n");
    logcatPattern.start();

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

    final ch.qos.logback.classic.Logger log = context.getLogger(Logger.ROOT_LOGGER_NAME);
    log.addAppender(fileAppender);
    log.addAppender(logcatAppender);
    log.setLevel(Level.INFO);
}
 
Example 16
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 17
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 18
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 19
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 20
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;
}