Java Code Examples for ch.qos.logback.core.FileAppender

The following examples show how to use ch.qos.logback.core.FileAppender. These examples are extracted from open source projects. 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 Project: synopsys-detect   Source File: DiagnosticLogger.java    License: 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();

    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 Project: orion.server   Source File: LogService.java    License: Eclipse Public License 1.0 6 votes vote down vote up
@Override
public List<FileAppender<ILoggingEvent>> getFileAppenders() {
	List<FileAppender<ILoggingEvent>> fileAppenders = new LinkedList<FileAppender<ILoggingEvent>>();

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

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

	return fileAppenders;
}
 
Example 3
Source Project: orion.server   Source File: LogService.java    License: Eclipse Public License 1.0 6 votes vote down vote up
@Override
public FileAppender<ILoggingEvent> getFileAppender(String name) {
	if (name == null)
		return null;

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

			Appender<ILoggingEvent> appender = index.next();
			if (appender instanceof FileAppender
					&& name.equals(appender.getName()))
				return (FileAppender<ILoggingEvent>) appender;
		}
	}

	return null;
}
 
Example 4
Source Project: uavstack   Source File: LogBackHookProxy.java    License: Apache License 2.0 6 votes vote down vote up
private void figureoutLogConfiguration(Logger Logger, LinkedList<LogProfileInfo> list, String appid) {

        Iterator<Appender<ILoggingEvent>> appenders = Logger.iteratorForAppenders();
        while (appenders != null && appenders.hasNext()) {
            Appender<ILoggingEvent> appender = appenders.next();
            if (appender instanceof FileAppender<?>) {
                getAppenderInfo((FileAppender<ILoggingEvent>)appender, list, appid);
            }
            else if(appender instanceof AsyncAppender) {
                Iterator<Appender<ILoggingEvent>> itAppenders = (Iterator<Appender<ILoggingEvent>>)((AsyncAppender) appender).iteratorForAppenders();
                while (itAppenders != null && itAppenders.hasNext()) {
                    Appender<ILoggingEvent> ap = itAppenders.next();
                    if (ap instanceof FileAppender<?>) {
                        getAppenderInfo((FileAppender<ILoggingEvent>)ap, list, appid);
                    }
                } 
            }
        }
    }
 
Example 5
Source Project: hub-detect   Source File: DiagnosticLogger.java    License: 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 6
Source Project: audiveris   Source File: LogUtil.java    License: 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 7
Source Project: audiveris   Source File: LogUtil.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Add a specific appender meant for FILE.
 */
public static void addFileAppender ()
{
    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("FILE");
    fileAppender.setContext(loggerContext);
    fileAppender.setAppend(false);

    String now = new SimpleDateFormat("yyyyMMdd'T'HHmmss").format(new Date());
    Path logPath = WellKnowns.LOG_FOLDER.resolve(now + ".log").toAbsolutePath();
    fileAppender.setFile(logPath.toString());
    fileEncoder.setContext(loggerContext);
    fileEncoder.setPattern(
            "%date %-5level [%X{BOOK}%X{SHEET}] %25replace(%file){'\\.java$',''} %-4line | %msg%n%ex");
    fileEncoder.start();
    fileAppender.setEncoder(fileEncoder);
    fileAppender.start();
    root.addAppender(fileAppender);

    initMessage("LogUtil. Logging to " + logPath);
}
 
Example 8
Source Project: jlineup   Source File: Utils.java    License: Apache License 2.0 6 votes vote down vote up
public static void logToFile(String workingDir) {
    LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    PatternLayoutEncoder ple = new PatternLayoutEncoder();

    ple.setPattern("%date %level [%thread] %logger{10} [%file:%line] %msg%n");
    ple.setContext(lc);
    ple.start();
    FileAppender<ILoggingEvent> fileAppender = new FileAppender<>();
    fileAppender.setName(JLINEUP_FILE_APPENDER);
    fileAppender.setFile(workingDir + "/jlineup.log");
    fileAppender.setEncoder(ple);
    fileAppender.setContext(lc);
    fileAppender.start();

    ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger)LoggerFactory.getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME);
    logger.addAppender(fileAppender);
    logger.setLevel(Level.DEBUG);
}
 
Example 9
Source Project: mirror   Source File: LoggingConfig.java    License: Apache License 2.0 6 votes vote down vote up
public synchronized static void enableLogFile() {
  init();

  LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();

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

  FileAppender<ILoggingEvent> file = new FileAppender<>();
  file.setContext(context);
  file.setAppend(true);
  file.setFile("mirror.log");
  file.setEncoder(encoder);
  file.start();
  getRootLogger().addAppender(file);
}
 
Example 10
Source Project: pravega   Source File: SelfTestRunner.java    License: Apache License 2.0 6 votes vote down vote up
private static void setupLogging(TestConfig testConfig) {
    val logFile = new java.io.File(testConfig.getTestLogPath());
    if (logFile.delete()) {
        TestLogger.log("Main", "Deleted log file %s.", logFile.getAbsolutePath());
    }

    // Configure slf4j to not log anything (console or whatever). This interferes with the console interaction.
    LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
    context.getLoggerList().get(0).detachAndStopAllAppenders();

    val fa = new FileAppender<ILoggingEvent>();
    fa.setContext(context);
    fa.setName("selftest");
    fa.setFile(logFile.getAbsolutePath());

    val encoder = new PatternLayoutEncoder();
    encoder.setContext(context);
    encoder.setPattern("%date{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %level - %msg%n");
    encoder.start();
    fa.setEncoder(encoder);
    fa.start();

    context.getLoggerList().get(0).addAppender(fa);
    context.getLoggerList().get(0).setLevel(Level.INFO);
    //context.reset();
}
 
Example 11
Source Project: baleen   Source File: BaleenLoggerBuilderTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testFileWithDailyRolling() {
  BaleenFileLoggerBuilder builder =
      new BaleenFileLoggerBuilder(
          NAME,
          BaleenLogging.DEFAULT_PATTERN,
          LOG_FILENAME,
          new MinMaxFilter(Level.INFO, Level.WARN),
          true,
          Optional.of(5),
          Optional.of(10));

  LoggerContext context = new LoggerContext();
  Encoder<ILoggingEvent> encoder = new PatternLayoutEncoder();

  Appender<ILoggingEvent> appender = builder.build(context, encoder);

  assertTrue(appender instanceof FileAppender);
  assertEquals(encoder, ((FileAppender<ILoggingEvent>) appender).getEncoder());

  // TODO: Add tests on the (current private) methods
}
 
Example 12
Source Project: baleen   Source File: BaleenLoggerBuilderTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testFileWithDailyRollingWithoutSize() {
  BaleenFileLoggerBuilder builder =
      new BaleenFileLoggerBuilder(
          NAME,
          BaleenLogging.DEFAULT_PATTERN,
          LOG_FILENAME,
          new MinMaxFilter(Level.INFO, Level.WARN),
          true,
          Optional.empty(),
          Optional.of(10));

  LoggerContext context = new LoggerContext();
  Encoder<ILoggingEvent> encoder = new PatternLayoutEncoder();

  Appender<ILoggingEvent> appender = builder.build(context, encoder);

  assertTrue(appender instanceof FileAppender);
  assertEquals(encoder, ((FileAppender<ILoggingEvent>) appender).getEncoder());

  // TODO: Add tests on the (current private) methods
}
 
Example 13
Source Project: baleen   Source File: BaleenLoggerBuilderTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testFileWithoutDailyRolling() {
  BaleenFileLoggerBuilder builder =
      new BaleenFileLoggerBuilder(
          NAME,
          BaleenLogging.DEFAULT_PATTERN,
          LOG_FILENAME,
          new MinMaxFilter(Level.INFO, Level.WARN),
          false,
          Optional.of(5),
          Optional.of(10));

  LoggerContext context = new LoggerContext();
  Encoder<ILoggingEvent> encoder = new PatternLayoutEncoder();

  Appender<ILoggingEvent> appender = builder.build(context, encoder);

  assertTrue(appender instanceof FileAppender);
  assertEquals(encoder, ((FileAppender<ILoggingEvent>) appender).getEncoder());

  // TODO: Add tests on the (current private) methods
}
 
Example 14
Source Project: skywalking   Source File: ContainerLogger.java    License: 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 15
Source Project: yangtools   Source File: Main.java    License: 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 16
Source Project: seed   Source File: LogbackLogManager.java    License: 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 17
Source Project: gocd   Source File: DefaultPluginLoggingService.java    License: 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 18
Source Project: gocd   Source File: DefaultPluginLoggingServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
private void assertPluginLogFile(String pluginId, String expectedPluginLogFileName) {
    SystemEnvironment systemEnvironment = mock(SystemEnvironment.class);

    DefaultPluginLoggingService loggingService = new DefaultPluginLoggingService(systemEnvironment);
    loggingService.debug(pluginId, "some-logger-name", "message");

    ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger("plugin." + pluginId);
    ArrayList<Appender<ILoggingEvent>> appenders = new ArrayList<>();
    logger.iteratorForAppenders().forEachRemaining(new Consumer<Appender<ILoggingEvent>>() {
        @Override
        public void accept(Appender<ILoggingEvent> iLoggingEventAppender) {
            appenders.add(iLoggingEventAppender);
        }
    });

    String loggingDirectory = loggingService.getCurrentLogDirectory();
    assertThat(appenders.size()).isEqualTo(1);
    assertThat(new File(((FileAppender) appenders.get(0)).rawFileProperty())).isEqualTo(new File(loggingDirectory, expectedPluginLogFileName));
}
 
Example 19
Source Project: gocd   Source File: FileLocationProvider.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, Object> asJson() {
    LinkedHashMap<String, Object> json = new LinkedHashMap<>();
    json.put("loc.config.dir", systemEnvironment.configDir().getAbsolutePath());

    List<Logger> loggers = LOGGER_CONTEXT.getLoggerList();

    Appender[] appenders = getAppenders(loggers);

    for (int i = 0; i < appenders.length; i++) {
        Appender appender = appenders[i];
        if (!isFileAppender(appender)) {
            continue;
        }
        FileAppender fileAppender = (FileAppender) appender;
        File logFile = new File(fileAppender.rawFileProperty());
        json.put("loc.log.root." + i, new File(logFile.getAbsolutePath()).getParent());
        json.put("loc.log.basename." + i, logFile.getName());
    }

    return json;
}
 
Example 20
Source Project: Hive2Hive   Source File: LoggerMenu.java    License: 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 21
/**
 * @{inheritDoc}
 */
@Override
public void store(Item item, String alias) {
    if (initialized) {
        FileAppender<ILoggingEvent> appender = appenders.get(alias);
        if (appender == null) {
            synchronized (appenders) {
                // do a second check in case one exists by now
                if (!appenders.containsKey(alias)) {
                    appender = createNewAppender(alias);
                    appenders.put(alias, appender);
                }
            }
        }

        ItemLoggingEvent event = new ItemLoggingEvent(item);
        appender.doAppend(event);
        logger.debug("Logged item '{}' to file '{}.log'", new String[] { item.getName(), alias });
    }
}
 
Example 22
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 23
/**
 * 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 24
Source Project: konduit-serving   Source File: LogUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Gets the file where the logs are.
 * @return the logs file.
 */
public static File getEndpointLogsFile() {
    Logger rootLogger = (Logger) LoggerFactory.getLogger(ROOT_LOGGER);
    FileAppender<ILoggingEvent> fileAppender = (FileAppender<ILoggingEvent>) rootLogger.getAppender("FILE");

    if(fileAppender != null) {
        return new File(fileAppender.getFile());
    } else {
        return null;
    }
}
 
Example 25
Source Project: konduit-serving   Source File: LogUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Sets the file appender with the name of "FILE" if needed. If it's already been setup,
 * it would be ignored.
 */
public static void setFileAppenderIfNeeded() {
    SysOutOverSLF4J.sendSystemOutAndErrToSLF4J();

    File previousLogsFile = getEndpointLogsFile();

    File newLogsFile = new File(DirectoryFetcher.getEndpointLogsDir(), Constants.MAIN_ENDPOINT_LOGS_FILE);

    if(!newLogsFile.equals(previousLogsFile)) {
        Logger rootLogger = (Logger) LoggerFactory.getLogger(ROOT_LOGGER);

        LoggerContext context = (LoggerContext) org.slf4j.LoggerFactory.getILoggerFactory();

        if(previousLogsFile != null) {
            rootLogger.detachAppender("FILE");
        }

        FileAppender<ILoggingEvent> fileAppender = new FileAppender<>();
        fileAppender.setName("FILE");
        fileAppender.setFile(newLogsFile.getAbsolutePath());
        fileAppender.setContext(context);

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

        fileAppender.setEncoder(patternLayoutEncoder);
        fileAppender.start();

        rootLogger.addAppender(fileAppender);
    }
}
 
Example 26
Source Project: java-trader   Source File: AccountImpl.java    License: 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 27
Source Project: arthas   Source File: LogbackHelper.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("rawtypes")
private static List<Map<String, Object>> doGetLoggerAppenders(Iterator<Appender<ILoggingEvent>> appenders) {
    List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();

    while (appenders.hasNext()) {
        Map<String, Object> info = new LinkedHashMap<String, Object>();
        Appender<ILoggingEvent> appender = appenders.next();
        info.put(LoggerHelper.name, appender.getName());
        info.put(LoggerHelper.clazz, appender.getClass());
        if (appender instanceof FileAppender) {
            info.put(LoggerHelper.file, ((FileAppender) appender).getFile());
        } else if (appender instanceof AsyncAppender) {
            AsyncAppender aa = (AsyncAppender) appender;
            Iterator<Appender<ILoggingEvent>> iter = aa.iteratorForAppenders();
            List<Map<String, Object>> asyncs = doGetLoggerAppenders(iter);

            // 异步appender所 ref的 appender,参考: https://logback.qos.ch/manual/appenders.html
            List<String> appenderRef = new ArrayList<String>();
            for (Map<String, Object> a : asyncs) {
                appenderRef.add((String) a.get(LoggerHelper.name));
                result.add(a);
            }
            info.put(LoggerHelper.appenderRef, appenderRef);
            info.put(LoggerHelper.blocking, !aa.isNeverBlock());
        } else if (appender instanceof ConsoleAppender) {
            info.put(LoggerHelper.target, ((ConsoleAppender) appender).getTarget());
        }
        result.add(info);
    }

    return result;
}
 
Example 28
Source Project: MMDownloader   Source File: MaruLoggerFactory.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 에러 내용을 파일로 저장하는 Logger 를 가져온다.
 *
 * @param logFileName 저장될 로그파일의 절대경로
 * @return 에러 출력 & 저장용 Logger 객체
 */
public static Logger getErrorLogger(String logFileName) {
	LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
	PatternLayoutEncoder encoder = getEncoder(loggerContext, "[%d{yyyy-MM-dd HH:mm:ss}][%-5level][%thread][%class{0}:%line] %msg%n");

	String loggerName = "ErrorLogger";
	FileAppender fileAppender = getFileAppender(loggerContext, encoder, logFileName, loggerName);

	Logger logger = loggerContext.getLogger(loggerName);
	logger.addAppender(fileAppender);
	logger.setAdditive(false);

	return logger;
}
 
Example 29
Source Project: orion.server   Source File: LogService.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Override
public RollingFileAppender<ILoggingEvent> getRollingFileAppender(String name) {
	FileAppender<ILoggingEvent> fileAppender = getFileAppender(name);
	if (fileAppender == null)
		return null;

	if (fileAppender instanceof RollingFileAppender<?>)
		return (RollingFileAppender<ILoggingEvent>) fileAppender;

	return null;
}
 
Example 30
Source Project: orion.server   Source File: FileAppenderResource.java    License: Eclipse Public License 1.0 5 votes vote down vote up
public FileAppenderResource(FileAppender<ILoggingEvent> fileAppender,
		URI baseLocation) {

	this.baseLocation = baseLocation;
	this.name = fileAppender.getName();
	this.isAppend = fileAppender.isAppend();
	this.isPrudent = fileAppender.isPrudent();
	this.isStarted = fileAppender.isStarted();
}