ch.qos.logback.core.FileAppender Java Examples

The following examples show how to use ch.qos.logback.core.FileAppender. 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: LogService.java    From orion.server with 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 #5
Source File: LogService.java    From orion.server with 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 #6
Source File: LoggingPersistenceService.java    From openhab1-addons with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * @{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 #7
Source File: FileLocationProvider.java    From gocd with 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 #8
Source File: DefaultPluginLoggingServiceTest.java    From gocd with 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 #9
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 #10
Source File: BaleenLoggerBuilderTest.java    From baleen with 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 #11
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 #12
Source File: LogBackHookProxy.java    From uavstack with 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 #13
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 #14
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 #15
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 #16
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 #17
Source File: LogUtil.java    From audiveris with 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 #18
Source File: BaleenLoggerBuilderTest.java    From baleen with 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 #19
Source File: Utils.java    From jlineup with 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 #20
Source File: BaleenLoggerBuilderTest.java    From baleen with 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 #21
Source File: LoggingConfig.java    From mirror with 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 #22
Source File: SelfTestRunner.java    From pravega with 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 #23
Source File: JarBimServer.java    From BIMserver with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Add a file appender to every logger we can find (the loggers should already have been configured via logback.xml)
 * 
 * @throws IOException
 */
private void fixLogging(BimServerConfig config) throws IOException {
	Path logFolder = config.getHomeDir().resolve("logs");
	if (!Files.isDirectory(logFolder)) {
		Files.createDirectories(logFolder);
	}
	Path file = logFolder.resolve("bimserver.log");

	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<ILoggingEvent>();
	String filename = file.toAbsolutePath().toString();

	if (lc instanceof LoggerContext) {
	    if (!lc.isStarted()) {
	    	lc.start();
	    }
	}
	
	System.out.println("Logging to " + filename);
	
	fileAppender.setFile(filename);
	fileAppender.setEncoder(ple);
	fileAppender.setContext(lc);
	fileAppender.start();

	for (ch.qos.logback.classic.Logger log : lc.getLoggerList()) {
		if (log.getLevel() != null) {
			log.addAppender(fileAppender);
		}
	}
}
 
Example #24
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 #25
Source File: DefaultPluginLoggingService.java    From gocd with Apache License 2.0 5 votes vote down vote up
private void initializeLoggerForPluginId(String pluginId) {
    if (alreadyInitialized(pluginId)) {
        return;
    }

    synchronized (pluginId.intern()) {
        if (alreadyInitialized(pluginId)) {
            return;
        }

        synchronized (appenderCreationLock) {
            FileAppender<ILoggingEvent> pluginAppender = getAppender(pluginId);

            ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(PLUGIN_LOGGER_PREFIX + "." + pluginId);
            logger.setAdditive(false);
            logger.setLevel(systemEnvironment.pluginLoggingLevel(pluginId));
            logger.addAppender(pluginAppender);

            if (systemEnvironment.consoleOutToStdout()) {
                ConsoleAppender<ILoggingEvent> consoleAppender = new ConsoleAppender<>();
                consoleAppender.setEncoder(LogHelper.encoder("%d{ISO8601} %5p [%t] %c{1}:%L [plugin-" + pluginId + "] - %m%n"));
                logger.setAdditive(false);
                logger.setLevel(systemEnvironment.pluginLoggingLevel(pluginId));
                consoleAppender.start();
                logger.addAppender(consoleAppender);
            }

            loggingServiceLogger.debug("Plugin with ID: " + pluginId + " will log to: " + pluginAppender.rawFileProperty());
        }
    }
}
 
Example #26
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 #27
Source File: WarServerInitializer.java    From BIMserver with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Add a file appender to every logger we can find (the loggers should already have been configured via logback.xml)
 * 
 * @throws IOException
 */
private void fixLogging(BimServerConfig config) throws IOException {
	Path logFolder = config.getHomeDir().resolve("logs");
	if (!Files.isDirectory(logFolder)) {
		Files.createDirectories(logFolder);
	}
	Path file = logFolder.resolve("bimserver.log");

	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<ILoggingEvent>();
	String filename = file.toAbsolutePath().toString();

	if (lc instanceof LoggerContext) {
	    if (!lc.isStarted()) {
	    	lc.start();
	    }
	}
	
	System.out.println("Logging to " + filename);
	
	fileAppender.setFile(filename);
	fileAppender.setEncoder(ple);
	fileAppender.setContext(lc);
	fileAppender.start();

	for (ch.qos.logback.classic.Logger log : lc.getLoggerList()) {
		if (log.getLevel() != null) {
			log.addAppender(fileAppender);
		}
	}
}
 
Example #28
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 #29
Source File: DefaultPluginLoggingService.java    From gocd with Apache License 2.0 5 votes vote down vote up
String getCurrentLogDirectory() {
    try {
        FileAppender fileAppender = getGoServerLogFileAppender();
        String fileName = fileAppender.rawFileProperty();
        return new File(fileName).getAbsoluteFile().getParent();
    } catch (Exception e) {
        return ".";
    }
}
 
Example #30
Source File: LogbackLogManager.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Override
@Guarded(by = STARTED)
public Set<File> getLogFiles() {
  HashSet<File> files = new HashSet<>();

  for (Appender<?> appender : appenders()) {
    if (appender instanceof FileAppender) {
      String path = ((FileAppender<?>) appender).getFile();
      files.add(new File(path));
    }
  }

  return files;
}