Java Code Examples for ch.qos.logback.core.rolling.TimeBasedRollingPolicy#start()

The following examples show how to use ch.qos.logback.core.rolling.TimeBasedRollingPolicy#start() . 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: 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 3
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 4
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 5
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 6
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 7
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 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: 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 10
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 11
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 12
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 13
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 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: LogbackFactory.java    From bither-desktop-java with Apache License 2.0 4 votes vote down vote up
public static FileAppender<ILoggingEvent> buildFileAppender(LoggingConfiguration.FileConfiguration file,
                                                            LoggerContext context,
                                                            String logFormat) {
    final LogFormatter formatter = new LogFormatter(context, file.getTimeZone());

    if (logFormat != null) {
        formatter.setPattern(logFormat);
    }
    formatter.start();

    final FileAppender<ILoggingEvent> appender =
            file.isArchive() ? new RollingFileAppender<ILoggingEvent>() :
                    new FileAppender<ILoggingEvent>();

    appender.setAppend(true);
    appender.setContext(context);
    appender.setLayout(formatter);
    appender.setFile(file.getCurrentLogFilename());
    appender.setPrudent(false);

    addThresholdFilter(appender, file.getThreshold());

    if (file.isArchive()) {

        final DefaultTimeBasedFileNamingAndTriggeringPolicy<ILoggingEvent> triggeringPolicy =
                new DefaultTimeBasedFileNamingAndTriggeringPolicy<ILoggingEvent>();
        triggeringPolicy.setContext(context);

        final TimeBasedRollingPolicy<ILoggingEvent> rollingPolicy = new TimeBasedRollingPolicy<ILoggingEvent>();
        rollingPolicy.setContext(context);
        rollingPolicy.setFileNamePattern(file.getArchivedLogFilenamePattern());
        rollingPolicy.setTimeBasedFileNamingAndTriggeringPolicy(triggeringPolicy);
        triggeringPolicy.setTimeBasedRollingPolicy(rollingPolicy);
        rollingPolicy.setMaxHistory(file.getArchivedFileCount());

        ((RollingFileAppender<ILoggingEvent>) appender).setRollingPolicy(rollingPolicy);
        ((RollingFileAppender<ILoggingEvent>) appender).setTriggeringPolicy(triggeringPolicy);

        rollingPolicy.setParent(appender);
        rollingPolicy.start();
    }

    appender.stop();
    appender.start();

    return appender;
}
 
Example 16
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 17
Source File: LogbackFactory.java    From bither-desktop-java with Apache License 2.0 4 votes vote down vote up
public static FileAppender<ILoggingEvent> buildFileAppender(LoggingConfiguration.FileConfiguration file,
                                                            LoggerContext context,
                                                            String logFormat) {
    final LogFormatter formatter = new LogFormatter(context, file.getTimeZone());

    if (logFormat != null) {
        formatter.setPattern(logFormat);
    }
    formatter.start();

    final FileAppender<ILoggingEvent> appender =
            file.isArchive() ? new RollingFileAppender<ILoggingEvent>() :
                    new FileAppender<ILoggingEvent>();

    appender.setAppend(true);
    appender.setContext(context);
    appender.setLayout(formatter);
    appender.setFile(file.getCurrentLogFilename());
    appender.setPrudent(false);

    addThresholdFilter(appender, file.getThreshold());

    if (file.isArchive()) {

        final DefaultTimeBasedFileNamingAndTriggeringPolicy<ILoggingEvent> triggeringPolicy =
                new DefaultTimeBasedFileNamingAndTriggeringPolicy<ILoggingEvent>();
        triggeringPolicy.setContext(context);

        final TimeBasedRollingPolicy<ILoggingEvent> rollingPolicy = new TimeBasedRollingPolicy<ILoggingEvent>();
        rollingPolicy.setContext(context);
        rollingPolicy.setFileNamePattern(file.getArchivedLogFilenamePattern());
        rollingPolicy.setTimeBasedFileNamingAndTriggeringPolicy(triggeringPolicy);
        triggeringPolicy.setTimeBasedRollingPolicy(rollingPolicy);
        rollingPolicy.setMaxHistory(file.getArchivedFileCount());

        ((RollingFileAppender<ILoggingEvent>) appender).setRollingPolicy(rollingPolicy);
        ((RollingFileAppender<ILoggingEvent>) appender).setTriggeringPolicy(triggeringPolicy);

        rollingPolicy.setParent(appender);
        rollingPolicy.start();
    }

    appender.stop();
    appender.start();

    return appender;
}
 
Example 18
Source File: NsLog.java    From ns4_frame with Apache License 2.0 4 votes vote down vote up
private static void renameLoggingFile() {
     LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
     context.stop();
     context.reset();
     JoranConfigurator configurator = new JoranConfigurator();
     configurator.setContext(context);
     try {
         URL url = getResource(LogConstants.AUTOCONFIG_FILE, Thread.currentThread().getContextClassLoader());
         if (url == null) {
             throw new RuntimeException("init Log error,can't find logback.xml");
         }
         
         
         System.out.println("初始化File:"+url.getFile());
         
         
         configurator.doConfigure(url.getFile());
     } catch (JoranException e) {
     	
     	//读取文件读不到 读取流
     	try {
	configurator.doConfigure(getResourceAsStream(LogConstants.AUTOCONFIG_FILE, Thread.currentThread().getContextClassLoader()));
} catch (JoranException e1) {
	throw new RuntimeException(e.getMessage(), e1);
}
     	
     }

     String configFile = System.getProperty("configfile");
     if(configFile == null || "".equals(configFile)) {
     	configFile = "";
     	//System.out.println("ns_log.configfile is null");
     }else {
     	configFile = configFile.indexOf(".") != -1 ? configFile.substring(0, configFile.lastIndexOf(".")) : configFile;
     	configFile += "_";
     	//System.out.println("ns_log.configfile is configFile");
     }
     
     for (ch.qos.logback.classic.Logger logger : context.getLoggerList()) {
         Iterator<Appender<ILoggingEvent>> index = logger.iteratorForAppenders();
         while (index.hasNext()) {
             Appender<ILoggingEvent> appender = index.next();
             if (appender instanceof NSLogRollingFileAppender) {
                 NSLogRollingFileAppender fileAppender = ((NSLogRollingFileAppender) appender);
                 fileAppender.stop();
                 String fileName = fileAppender.getFile().replace("configfile_", configFile);
                 fileAppender.setFile(fileName);
                 //System.out.println("ns_log.filenNme:" + fileName);

                 TriggeringPolicy triggeringPolicy = fileAppender.getTriggeringPolicy();
                 if (triggeringPolicy instanceof TimeBasedRollingPolicy) {
                     TimeBasedRollingPolicy timeBasedRollingPolicy = ((TimeBasedRollingPolicy) triggeringPolicy);
                     String fileNamePattern = timeBasedRollingPolicy.getFileNamePattern().replace("configfile_", configFile);
                     timeBasedRollingPolicy.setFileNamePattern(fileNamePattern);
                     //System.out.println("ns_log.fileNamePattern:" + fileNamePattern);
                     timeBasedRollingPolicy.stop();
                     timeBasedRollingPolicy.start();
                 }
                 fileAppender.realStart();
             }
         }
     }
     context.start();
 }