Java Code Examples for ch.qos.logback.core.FileAppender#setFile()

The following examples show how to use ch.qos.logback.core.FileAppender#setFile() . 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: DiagnosticLogger.java    From synopsys-detect with Apache License 2.0 7 votes vote down vote up
private FileAppender<ILoggingEvent> addAppender(final String file) {
    final LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    final PatternLayoutEncoder ple = new PatternLayoutEncoder();

    ple.setPattern("%date %level [%file:%line] %msg%n");
    ple.setContext(lc);
    ple.start();

    final FileAppender<ILoggingEvent> appender;
    appender = new FileAppender<>();
    appender.setFile(file);
    appender.setEncoder(ple);
    appender.setContext(lc);
    final ThresholdFilter levelFilter = new ThresholdFilter();
    levelFilter.setLevel(this.level.levelStr);
    levelFilter.start();
    appender.addFilter(levelFilter);

    appender.start();

    final ch.qos.logback.classic.Logger logbackLogger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
    logbackLogger.addAppender(appender);

    return appender;
}
 
Example 2
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 3
Source File: LoggerMenu.java    From Hive2Hive with MIT License 6 votes vote down vote up
private static String createRootLogger() {
	LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
	PatternLayoutEncoder ple = new PatternLayoutEncoder();

	ple.setPattern("%d{HH:mm:ss} %-12.-12([%thread])[%-5level] %logger{0} -%msg%n");
	ple.setContext(loggerContext);
	ple.start();

	String fileName = String.format("logs/h2h-log %s.txt",
			new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss").format(System.currentTimeMillis()));
	FileAppender<ILoggingEvent> fileAppender = new FileAppender<ILoggingEvent>();
	fileAppender.setFile(fileName);
	fileAppender.setEncoder(ple);
	fileAppender.setContext(loggerContext);
	fileAppender.start();

	Logger logbackLogger = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME);
	logbackLogger.addAppender(fileAppender);
	logbackLogger.setLevel(Level.DEBUG);
	logbackLogger.setAdditive(false);

	return fileName;
}
 
Example 4
Source File: LoggingPersistenceService.java    From openhab1-addons with Eclipse Public License 2.0 6 votes vote down vote up
protected FileAppender<ILoggingEvent> createNewAppender(String alias) {
    LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();

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

    FileAppender<ILoggingEvent> appender = new FileAppender<ILoggingEvent>();
    appender.setAppend(true);
    appender.setFile(LOG_FOLDER + File.separator + alias + LOG_FILEEXT);
    appender.setEncoder(encoder);
    appender.setContext(context);
    appender.start();

    return appender;
}
 
Example 5
Source File: Main.java    From yangtools with Eclipse Public License 1.0 6 votes vote down vote up
private static void setOutput(final String... paths) {
    LOG_ROOT.getLoggerContext().reset();

    final PatternLayoutEncoder encoder = new PatternLayoutEncoder();
    encoder.setPattern("%date %level [%thread] [%file:%line] %msg%n");
    encoder.setContext(LOG_ROOT.getLoggerContext());
    encoder.start();

    for (final String path : paths) {
        // create FileAppender
        final FileAppender<ILoggingEvent> logfileOut = new FileAppender<>();
        logfileOut.setAppend(false);
        logfileOut.setFile(path);
        logfileOut.setContext(LOG_ROOT.getLoggerContext());
        logfileOut.setEncoder(encoder);
        logfileOut.start();

        // attach the rolling file appender to the root logger
        LOG_ROOT.addAppender(logfileOut);
    }
}
 
Example 6
Source File: DiagnosticLogger.java    From hub-detect with Apache License 2.0 6 votes vote down vote up
private FileAppender<ILoggingEvent> addAppender(final String file) {
    final LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    final PatternLayoutEncoder ple = new PatternLayoutEncoder();

    ple.setPattern("%date %level [%file:%line] %msg%n");
    ple.setContext(lc);
    ple.start();
    FileAppender<ILoggingEvent> appender;
    appender = new FileAppender<>();
    appender.setFile(file);
    appender.setEncoder(ple);
    appender.setContext(lc);
    appender.start();

    final ch.qos.logback.classic.Logger logbackLogger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(LOGBACK_LOGGER_NAME);
    logbackLogger.addAppender(appender);
    logbackLogger.setLevel(Level.ALL);

    return appender;
}
 
Example 7
Source File: LogUtil.java    From audiveris with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Start a specific file logging, typically for the processing of a given book.
 *
 * @param name      appender name (typically the book radix)
 * @param logFolder target folder where the log file is to be written
 */
public static void addAppender (String name,
                                Path logFolder)
{
    LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
    Logger root = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(
            Logger.ROOT_LOGGER_NAME);
    FileAppender fileAppender = new FileAppender();
    PatternLayoutEncoder fileEncoder = new PatternLayoutEncoder();
    fileAppender.setName(name);
    fileAppender.setContext(loggerContext);
    fileAppender.setAppend(false);

    String now = new SimpleDateFormat("yyyyMMdd'T'HHmm").format(new Date());
    Path logFile = logFolder.resolve(name + "-" + now + ".log");
    fileAppender.setFile(logFile.toAbsolutePath().toString());
    fileEncoder.setContext(loggerContext);
    fileEncoder.setPattern("%date %level [%X{BOOK}%X{SHEET}] %25file:%-4line | %msg%n%ex");
    fileEncoder.start();
    fileAppender.setEncoder(fileEncoder);
    fileAppender.start();
    root.addAppender(fileAppender);
}
 
Example 8
Source File: ContainerLogger.java    From skywalking with Apache License 2.0 6 votes vote down vote up
public ContainerLogger(final Path logDirectory, final String container) {

        final LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
        final PatternLayoutEncoder encoder = new PatternLayoutEncoder();

        encoder.setPattern("%d{HH:mm:ss.SSS} %-5level %logger{36}.%M - %msg%n");
        encoder.setContext(context);
        encoder.start();

        final FileAppender<ILoggingEvent> fileAppender = new FileAppender<>();
        fileAppender.setFile(logDirectory.resolve(container).toAbsolutePath().toString());
        fileAppender.setEncoder(encoder);
        fileAppender.setContext(context);
        fileAppender.start();

        final ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(container);
        logger.addAppender(fileAppender);
        logger.setLevel(Level.DEBUG);
        logger.setAdditive(false);

        this.delegate = logger;
    }
 
Example 9
Source File: SingularityRunnerBaseLogging.java    From Singularity with Apache License 2.0 5 votes vote down vote up
public FileAppender<ILoggingEvent> buildFileAppender(
  LoggerContext context,
  String file
) {
  FileAppender<ILoggingEvent> fileAppender = new FileAppender<>();
  fileAppender.setFile(file);
  fileAppender.setContext(context);
  fileAppender.setPrudent(true);

  PatternLayoutEncoder encoder = new PatternLayoutEncoder();
  encoder.setContext(context);
  encoder.setPattern(
    primaryConfiguration
      .getLoggingPattern()
      .orElse(
        baseConfiguration.getLoggingPattern().isPresent()
          ? baseConfiguration.getLoggingPattern().get()
          : JavaUtils.LOGBACK_LOGGING_PATTERN
      )
  );
  encoder.start();

  fileAppender.setEncoder(encoder);
  fileAppender.start();

  return fileAppender;
}
 
Example 10
Source File: LoggingTestWatcher.java    From helios with Apache License 2.0 5 votes vote down vote up
/**
 * Sets up a FileAppender under the path {@code $logDir/<timestamp>-<name>-<pid>.log}. If not set
 * as a system property then {@code $logDir} falls back to {@code /tmp/helios-test/log}.
 */
private void setupFileLogging(final String name) {
  final ch.qos.logback.classic.Logger rootLogger =
      (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(ROOT_LOGGER_NAME);
  final LoggerContext context = rootLogger.getLoggerContext();
  context.reset();

  final String ts = new SimpleDateFormat("yyyyMMdd'T'HHmmss.SSS").format(new Date());
  final String pid = ManagementFactory.getRuntimeMXBean().getName().split("@", 2)[0];

  final PatternLayoutEncoder ple = new PatternLayoutEncoder();
  ple.setContext(context);
  ple.setPattern("%d{HH:mm:ss.SSS} %-5level %logger{1} %F:%L - %msg%n");
  ple.start();

  final Path directory = Paths.get(System.getProperty("logDir", "/tmp/helios-test/log/"));
  final String filename = String.format("%s-%s-%s.log", ts, name, pid);
  final Path file = directory.resolve(filename);

  final FileAppender<ILoggingEvent> fileAppender = new FileAppender<>();
  fileAppender.setEncoder(ple);
  fileAppender.setFile(file.toString());
  fileAppender.setContext(context);
  fileAppender.start();

  rootLogger.setLevel(Level.DEBUG);
  rootLogger.addAppender(fileAppender);

  try {
    Files.createDirectories(directory);
  } catch (IOException e) {
    throw new RuntimeException(e);
  }

  configureLogger("org.eclipse.jetty", Level.ERROR);
  configureLogger("org.apache.curator", Level.ERROR);
  configureLogger("org.apache.zookeeper", Level.ERROR);
  configureLogger("com.spotify.helios", Level.DEBUG);
}
 
Example 11
Source File: LogbackUtils.java    From termsuite-core with Apache License 2.0 5 votes vote down vote up
public static OutputStreamAppender<ILoggingEvent> createFileAppender(Path path) {
	FileAppender<ILoggingEvent> fa = new FileAppender<ILoggingEvent>();
	fa.setFile(path.toString());
	fa.setAppend(true);
	fa.setName("FileLogger");
	return fa;
}
 
Example 12
Source File: DefaultPluginLoggingServiceIntegrationTest.java    From gocd with Apache License 2.0 5 votes vote down vote up
@Test
void shouldGetCurrentLogDirectoryByLookingAtFileAppenderOfRootLogger() {
    if (WINDOWS.satisfy()) {
        return;
    }
    FileAppender fileAppender = new FileAppender();
    fileAppender.setFile("/var/log/go-server/go-server.log");

    DefaultPluginLoggingService service = Mockito.spy(new DefaultPluginLoggingService(systemEnvironment));
    doReturn(fileAppender).when(service).getGoServerLogFileAppender();

    String currentLogDirectory = service.getCurrentLogDirectory();

    assertThat(currentLogDirectory).isEqualTo("/var/log/go-server");
}
 
Example 13
Source File: LogUtil.java    From obevo with Apache License 2.0 5 votes vote down vote up
private FileAppender<ILoggingEvent> createAppender(String logFilePath) {
    LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    PatternLayoutEncoder ple = new PatternLayoutEncoder();

    ple.setPattern("[%p] %c{1} [%t] %d{[M-dd HH:mm:ss]} - %m%n");
    ple.setContext(lc);
    ple.start();
    FileAppender<ILoggingEvent> fileAppender = new FileAppender<>();
    fileAppender.setFile(logFilePath);
    fileAppender.setEncoder(ple);
    fileAppender.setContext(lc);
    fileAppender.start();

    return fileAppender;
}
 
Example 14
Source File: AccountImpl.java    From java-trader with Apache License 2.0 5 votes vote down vote up
/**
 * 创建Account Logger
 * @param separateLogger true 会为每个Account创建一个日志文件: TRADER_HOME/work/<TRADING_DAY>/accountId.log
 */
private void createAccountLogger() {
    if ( !simMode ) {
        LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();

        FileAppender fileAppender = new FileAppender();
        fileAppender.setContext(loggerContext);
        fileAppender.setName("timestamp");
        // set the file name
        File logFile = new File(tradingWorkDir, id+".log");
        fileAppender.setFile(logFile.getAbsolutePath());

        PatternLayoutEncoder encoder = new PatternLayoutEncoder();
        encoder.setContext(loggerContext);
        encoder.setPattern("%d [%thread] %-5level %logger{35} - %msg %n");
        encoder.start();

        fileAppender.setEncoder(encoder);
        fileAppender.start();

        // attach the rolling file appender to the logger of your choice
        loggerCategory = AccountImpl.class.getName()+"."+id;
        ch.qos.logback.classic.Logger packageLogger = loggerContext.getLogger(loggerCategory);
        packageLogger.addAppender(fileAppender);
        packageLogger.setAdditive(true); //保证每个Account数据, 在主的日志中也有一份

        logger = loggerContext.getLogger(loggerCategory+"."+AccountImpl.class.getSimpleName());
    } else {
        loggerCategory = AccountImpl.class.getName();
        logger = LoggerFactory.getLogger(AccountImpl.class);
    }
}
 
Example 15
Source File: DiagnosticLogging.java    From hivemq-community-edition with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the trace log to the root logger. Also adds filter, to make sure that
 * the appender which are already defined for HiveMQ are not affected by this logging
 * level change.
 * <p>
 * <b>This will significantly slow down HiveMQ, since the root level loggers Level is changed
 * to the finest logging level!</b>
 *
 * @param filePath the file path
 */
static void setTraceLog(final String filePath) {

    log.info("Creating trace log {}", filePath);

    final Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
    final Level originalLoggingLevel = logger.getLevel();
    final Iterator<Appender<ILoggingEvent>> appenderIterator = logger.iteratorForAppenders();
    while (appenderIterator.hasNext()) {
        final Appender<ILoggingEvent> next = appenderIterator.next();
        next.addFilter(new PreserveOriginalLoggingLevelFilter(originalLoggingLevel));
    }

    final LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    final PatternLayoutEncoder ple = new PatternLayoutEncoder();

    ple.setPattern("%date %level [%thread] %logger{10} [%file:%line] %msg%n");
    ple.setContext(lc);
    ple.start();

    final FileAppender<ILoggingEvent> fileAppender = new FileAppender<>();
    fileAppender.setFile(filePath);
    fileAppender.setEncoder(ple);
    fileAppender.setContext(lc);
    fileAppender.start();

    logger.addAppender(fileAppender);
    logger.setLevel(Level.ALL);
    logger.setAdditive(false);
}
 
Example 16
Source File: LoggingHelper.java    From rpicheck with MIT License 4 votes vote down vote up
/**
 * Initialize and configure the logback logging.
 * Java configuration is used to rely on {@link Context#getExternalFilesDir(String)} to provide a storage directory.
 * This must be called on every "entry-point" to this app, e.g. Widget Configuration screen or MainActivity.
 *
 * @param context application context
 */
public static void initLogging(Context context) {
    final SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);
    boolean isDebugLogging = sharedPrefs.getBoolean(SettingsActivity.KEY_PREF_DEBUG_LOGGING, false);
    LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    lc.reset();
    // qualify Logger to disambiguate from org.slf4j.Logger
    ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
    root.setLevel(Level.TRACE);

    PatternLayoutEncoder encoder1 = new PatternLayoutEncoder();
    encoder1.setContext(lc);
    encoder1.setPattern("%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n");
    encoder1.start();

    // setup LogcatAppender
    PatternLayoutEncoder encoder2 = new PatternLayoutEncoder();
    encoder2.setContext(lc);
    encoder2.setPattern("[%thread] %msg%n");
    encoder2.start();

    LogcatAppender logcatAppender = new LogcatAppender();
    logcatAppender.setContext(lc);
    logcatAppender.setEncoder(encoder2);
    logcatAppender.start();

    // Log-Level for RaspiCheck
    ch.qos.logback.classic.Logger rpicheckLogger = (ch.qos.logback.classic.Logger) LoggerFactory
            .getLogger("de.eidottermihi.rpicheck");
    rpicheckLogger.setLevel(isDebugLogging ? Level.DEBUG : Level.INFO);
    ch.qos.logback.classic.Logger sshjLogger = (ch.qos.logback.classic.Logger) LoggerFactory
            .getLogger("net.schmizz");
    sshjLogger.setLevel(Level.WARN);

    // setup FileAppender
    String logPath = getLogfilePath(context);
    if (logPath != null) {
        FileAppender<ILoggingEvent> fileAppender = new FileAppender<ILoggingEvent>();
        fileAppender.setContext(lc);
        fileAppender.setFile(logPath);
        fileAppender.setEncoder(encoder1);
        fileAppender.start();
        rpicheckLogger.addAppender(fileAppender);
        sshjLogger.addAppender(fileAppender);
    }
    root.addAppender(logcatAppender);
    LOGGER.debug("Logging was configured, debug logging enabled: {}", isDebugLogging);
}
 
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: MvcApp.java    From AndroidMvc with Apache License 2.0 4 votes vote down vote up
private void configureLogbackDirectly() {
    // reset the default context (which may already have been initialized)
    // since we want to reconfigure it
    LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    lc.reset();

    // setup FileAppender
    PatternLayoutEncoder encoder1 = new PatternLayoutEncoder();
    encoder1.setContext(lc);
    encoder1.setPattern("%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n");
    encoder1.start();

    FileAppender<ILoggingEvent> fileAppender = new FileAppender<>();
    fileAppender.setContext(lc);
    fileAppender.setFile(this.getFileStreamPath("app.log").getAbsolutePath());
    fileAppender.setEncoder(encoder1);
    fileAppender.start();

    // setup LogcatAppender
    PatternLayoutEncoder encoder2 = new PatternLayoutEncoder();
    encoder2.setContext(lc);
    encoder2.setPattern("[%thread] %msg%n");
    encoder2.start();

    LogcatAppender logcatAppender = new LogcatAppender();
    logcatAppender.setContext(lc);
    logcatAppender.setEncoder(encoder2);
    logcatAppender.start();

    // backup the newly created appenders to the root logger;
    // qualify Logger to disambiguate from org.slf4j.Logger
    ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
    root.addAppender(fileAppender);
    root.addAppender(logcatAppender);

    if (BuildConfig.DEBUG) {
        root.setLevel(Level.ALL);
    } else {
        root.setLevel(Level.INFO);
    }
}
 
Example 19
Source File: LogbackConfiguration.java    From IridiumApplicationTesting with MIT License 4 votes vote down vote up
@Override
public void configureLogging(@NotNull final String logfile) {
	checkArgument(StringUtils.isNotBlank(logfile));

	try {
		final LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();

		final FileAppender<ILoggingEvent> fileAppender = new FileAppender<>();
		fileAppender.setContext(loggerContext);
		fileAppender.setName("timestamp");
		// set the file name
		fileAppender.setFile(logfile);

		final PatternLayoutEncoder encoder = new PatternLayoutEncoder();
		encoder.setContext(loggerContext);
		encoder.setPattern("%r %thread %level - %msg%n");
		encoder.start();

		fileAppender.setEncoder(encoder);
		fileAppender.start();

		// attach the rolling file appender to the logger of your choice
		final Logger logbackLogger =
			(Logger) LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
		logbackLogger.addAppender(fileAppender);

		/*
			We only want to hear about errors from the libraries that are used by Iridium
		 */
		logbackLogger.setLevel(Level.ERROR);

		/*
			Our own code should be info level
		 */
		final Logger iridiumLogger =
			(Logger) LoggerFactory.getLogger("au.com.agic");
		iridiumLogger.setLevel(Level.INFO);

		/*
			Performance increase for redirected JUL loggers
		 */
		final LevelChangePropagator levelChangePropagator = new LevelChangePropagator();
		levelChangePropagator.setContext(loggerContext);
		levelChangePropagator.setResetJUL(true);
		loggerContext.addListener(levelChangePropagator);

		/*
			Redirect java logging and sys out to slf4j
		 */
		LogManager.getLogManager().reset();
		SLF4JBridgeHandler.removeHandlersForRootLogger();
		SysOutOverSLF4J.sendSystemOutAndErrToSLF4J();
		SLF4JBridgeHandler.install();
	} catch (final Exception ex) {
		LOGGER.error("WEBAPPTESTER-BUG-0006: Could not configure Logback", ex);
	}
}
 
Example 20
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;
}