Search in sources :

Example 1 with OutputStreamAppender

use of ch.qos.logback.core.OutputStreamAppender in project UniversalMediaServer by UniversalMediaServer.

the class LoggingTest method testLoggingConfig.

@Test
public void testLoggingConfig() throws ConfigurationException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
    // Set up a test (default) configuration
    PMS.get();
    PmsConfiguration configuration = new PmsConfiguration(false);
    PMS.setConfiguration(configuration);
    // Load logback configuration
    LoggingConfig.loadFile();
    // Silence logger
    LoggingConfig.setRootLevel(Level.OFF);
    // Get access to logger
    LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
    Logger rootLogger = context.getLogger(Logger.ROOT_LOGGER_NAME);
    /* During UMS build a valid configuration should be accessible at least under "external resources"
		 * and thus testing for a valid configuration is considered OK to be able to do the other tests.
		 * "internal defaults" is returned if a valid configuration can't be found.
		 */
    // Test for a valid configuration
    File file = new File(LoggingConfig.getConfigFilePath());
    assertTrue("LoggingConfigIsFile", file.isFile());
    assertFalse("LoggingConfigIsFile", file.isDirectory());
    // Test getLogFilePaths() and LoggingConfigFileLoader.getLogFilePaths()
    HashMap<String, String> logFilePaths = LoggingConfig.getLogFilePaths();
    @SuppressWarnings("deprecation") HashMap<String, String> compLogFilePaths = LoggingConfigFileLoader.getLogFilePaths();
    Iterator<Appender<ILoggingEvent>> iterator = rootLogger.iteratorForAppenders();
    while (iterator.hasNext()) {
        Appender<ILoggingEvent> appender = iterator.next();
        if (appender instanceof FileAppender) {
            FileAppender<ILoggingEvent> fa = (FileAppender<ILoggingEvent>) appender;
            assertTrue("LogFilePathsContainsKey", logFilePaths.containsKey(fa.getName()));
            assertEquals("LogFilePathsHasPath", logFilePaths.get(fa.getName()), fa.getFile());
            if (fa.getName().equals("default.log")) {
                assertTrue("CompatibleLogFilePathsContainsKey", compLogFilePaths.containsKey("debug.log"));
                assertEquals("CompatibleLogFilePathsHasPath", compLogFilePaths.get("debug.log"), fa.getFile());
            } else {
                assertTrue("CompatibleLogFilePathsContainsKey", compLogFilePaths.containsKey(fa.getName()));
                assertEquals("CompatibleLogFilePathsHasPath", compLogFilePaths.get(fa.getName()), fa.getFile());
            }
        }
    }
    // Reset LogBack configuration and create a fake one to not rely on the existing configuration file
    context.reset();
    TestFileAppender<ILoggingEvent> testDefaultAppender = new TestFileAppender<>();
    testDefaultAppender.setName("default.log");
    testDefaultAppender.setContext(context);
    PatternLayoutEncoder layoutEncoder = new PatternLayoutEncoder();
    layoutEncoder.setPattern("%-5level %d{HH:mm:ss.SSS} [%thread] %msg%n");
    layoutEncoder.setContext(context);
    testDefaultAppender.setEncoder(layoutEncoder);
    rootLogger.addAppender(testDefaultAppender);
    TestFileAppender<ILoggingEvent> testGenericAppender = new TestFileAppender<>();
    testGenericAppender.setName("SomeOtherFileAppender");
    testGenericAppender.setContext(context);
    layoutEncoder = new PatternLayoutEncoder();
    layoutEncoder.setPattern("%-5level %d %msg%n");
    layoutEncoder.setContext(context);
    testGenericAppender.setEncoder(layoutEncoder);
    rootLogger.addAppender(testGenericAppender);
    TestAppender<ILoggingEvent> testNonFileAppender = new TestAppender<>();
    testNonFileAppender.setName("SomeNonFileAppender");
    testNonFileAppender.setContext(context);
    rootLogger.addAppender(testNonFileAppender);
    // Test setBuffered()
    LoggingConfig.setBuffered(true);
    iterator = rootLogger.iteratorForAppenders();
    while (iterator.hasNext()) {
        Appender<ILoggingEvent> appender = iterator.next();
        if (appender instanceof OutputStreamAppender && !(appender instanceof ConsoleAppender<?>)) {
            // Appender has ImmediateFlush property
            assertFalse("LogFileIsBuffered", ((OutputStreamAppender<ILoggingEvent>) appender).isImmediateFlush());
        }
    }
    LoggingConfig.setBuffered(false);
    iterator = rootLogger.iteratorForAppenders();
    while (iterator.hasNext()) {
        Appender<ILoggingEvent> appender = iterator.next();
        if (appender instanceof OutputStreamAppender && !(appender instanceof ConsoleAppender<?>)) {
            assertTrue("LogFileIsNotBuffered", ((OutputStreamAppender<ILoggingEvent>) appender).isImmediateFlush());
        // Appender has ImmediateFlush property
        }
    }
    // Test getRootLevel()
    assertEquals("GetRootLevel", LoggingConfig.getRootLevel(), rootLogger.getLevel());
    // Test setRootLevel()
    LoggingConfig.setRootLevel(Level.ALL);
    assertEquals("SetRootLevel", LoggingConfig.getRootLevel(), Level.ALL);
    LoggingConfig.setRootLevel(Level.INFO);
    assertEquals("SetRootLevel", LoggingConfig.getRootLevel(), Level.INFO);
    LoggingConfig.setRootLevel(Level.OFF);
    // Test setConsoleFilter()
    configuration.setLoggingFilterConsole(Level.WARN);
    ConsoleAppender<ILoggingEvent> consoleAppender = new ConsoleAppender<>();
    consoleAppender.setContext(context);
    PatternLayoutEncoder patternEncoder = new PatternLayoutEncoder();
    patternEncoder.setPattern("%msg%n");
    patternEncoder.setContext(context);
    patternEncoder.start();
    consoleAppender.setEncoder(patternEncoder);
    consoleAppender.start();
    rootLogger.addAppender(consoleAppender);
    LoggingConfig.setConsoleFilter();
    List<Filter<ILoggingEvent>> filterList = consoleAppender.getCopyOfAttachedFiltersList();
    assertEquals("NumberOfConsoleFilters", filterList.size(), 1);
    assertTrue("ConsoleFilterIsThresholdFilter", filterList.get(0) instanceof ThresholdFilter);
    ThresholdFilter thresholdFilter = (ThresholdFilter) filterList.get(0);
    Field field = thresholdFilter.getClass().getDeclaredField("level");
    field.setAccessible(true);
    assertEquals("ConsoleFilterLevel", field.get(thresholdFilter), Level.WARN);
    configuration.setLoggingFilterConsole(Level.TRACE);
    LoggingConfig.setConsoleFilter();
    filterList = consoleAppender.getCopyOfAttachedFiltersList();
    assertEquals("NumberOfConsoleFilters", filterList.size(), 1);
    assertTrue("ConsoleFilterIsThresholdFilter", filterList.get(0) instanceof ThresholdFilter);
    thresholdFilter = (ThresholdFilter) filterList.get(0);
    field = thresholdFilter.getClass().getDeclaredField("level");
    field.setAccessible(true);
    assertEquals("ConsoleFilterLevel", field.get(thresholdFilter), Level.TRACE);
    rootLogger.detachAppender(consoleAppender);
    // Test setTracesFilter()
    configuration.setLoggingFilterLogsTab(Level.WARN);
    FrameAppender<ILoggingEvent> frameAppender = new FrameAppender<>();
    frameAppender.setContext(context);
    patternEncoder = new PatternLayoutEncoder();
    patternEncoder.setPattern("%msg%n");
    patternEncoder.setContext(context);
    patternEncoder.start();
    frameAppender.setEncoder(patternEncoder);
    frameAppender.start();
    rootLogger.addAppender(frameAppender);
    LoggingConfig.setTracesFilter();
    filterList = frameAppender.getCopyOfAttachedFiltersList();
    assertEquals("NumberOfTracesFilters", filterList.size(), 1);
    assertTrue("TracesFilterIsThresholdFilter", filterList.get(0) instanceof ThresholdFilter);
    thresholdFilter = (ThresholdFilter) filterList.get(0);
    field = thresholdFilter.getClass().getDeclaredField("level");
    field.setAccessible(true);
    assertEquals("TracesFilterLevel", field.get(thresholdFilter), Level.WARN);
    configuration.setLoggingFilterLogsTab(Level.TRACE);
    LoggingConfig.setTracesFilter();
    filterList = frameAppender.getCopyOfAttachedFiltersList();
    assertEquals("NumberOfTracesFilters", filterList.size(), 1);
    assertTrue("TracesFilterIsThresholdFilter", filterList.get(0) instanceof ThresholdFilter);
    thresholdFilter = (ThresholdFilter) filterList.get(0);
    field = thresholdFilter.getClass().getDeclaredField("level");
    field.setAccessible(true);
    assertEquals("TracesFilterLevel", field.get(thresholdFilter), Level.TRACE);
    rootLogger.detachAppender(frameAppender);
    // Test isSyslogDisabled()
    if (syslogAppenderFound(rootLogger.iteratorForAppenders())) {
        assertTrue("SyslogDisabledByConfiguration", LoggingConfig.isSyslogDisabled());
    } else {
        assertFalse("SyslogNotDisabledByConfiguration", LoggingConfig.isSyslogDisabled());
    }
    // Test setSyslog() if possible
    if (!syslogAppenderFound(rootLogger.iteratorForAppenders())) {
        configuration.setLoggingSyslogHost("localhost");
        configuration.setLoggingUseSyslog(true);
        LoggingConfig.setSyslog();
        assertTrue("SyslogEnabled", syslogAppenderFound(rootLogger.iteratorForAppenders()));
        configuration.setLoggingUseSyslog(false);
        LoggingConfig.setSyslog();
        assertFalse("SyslogDisabled", syslogAppenderFound(rootLogger.iteratorForAppenders()));
    }
    // Test forceVerboseFileEncoder() given that LogBack configuration
    // contains at least one file appender with PatternLayoutEncoder
    LoggingConfig.forceVerboseFileEncoder();
    iterator = rootLogger.iteratorForAppenders();
    while (iterator.hasNext()) {
        Appender<ILoggingEvent> appender = iterator.next();
        if (appender instanceof OutputStreamAppender && !(appender instanceof ConsoleAppender<?>)) {
            // Appender has Encoder property
            Encoder<ILoggingEvent> encoder = ((OutputStreamAppender<ILoggingEvent>) appender).getEncoder();
            if (encoder instanceof PatternLayoutEncoder) {
                // Encoder has pattern
                patternEncoder = (PatternLayoutEncoder) encoder;
                assertTrue("AppenderPatternHasCorrectTimestamp", patternEncoder.getPattern().matches(".*%(d|date)\\{yyyy-MM-dd HH:mm:ss.SSS\\}.*"));
                assertTrue("AppenderPatternHasLogger", patternEncoder.getPattern().matches(".*%logger.*"));
            }
        }
    }
    context.reset();
}
Also used : ConsoleAppender(ch.qos.logback.core.ConsoleAppender) ThresholdFilter(ch.qos.logback.classic.filter.ThresholdFilter) OutputStreamAppender(ch.qos.logback.core.OutputStreamAppender) Logger(ch.qos.logback.classic.Logger) ILoggingEvent(ch.qos.logback.classic.spi.ILoggingEvent) Field(java.lang.reflect.Field) PmsConfiguration(net.pms.configuration.PmsConfiguration) ConsoleAppender(ch.qos.logback.core.ConsoleAppender) OutputStreamAppender(ch.qos.logback.core.OutputStreamAppender) FileAppender(ch.qos.logback.core.FileAppender) SyslogAppender(ch.qos.logback.classic.net.SyslogAppender) Appender(ch.qos.logback.core.Appender) FileAppender(ch.qos.logback.core.FileAppender) PatternLayoutEncoder(ch.qos.logback.classic.encoder.PatternLayoutEncoder) LoggerContext(ch.qos.logback.classic.LoggerContext) ThresholdFilter(ch.qos.logback.classic.filter.ThresholdFilter) Filter(ch.qos.logback.core.filter.Filter) File(java.io.File) Test(org.junit.Test)

Example 2 with OutputStreamAppender

use of ch.qos.logback.core.OutputStreamAppender in project UniversalMediaServer by UniversalMediaServer.

the class LoggingConfig method forceVerboseFileEncoder.

public static synchronized void forceVerboseFileEncoder() {
    final String timeStampFormat = "yyyy-MM-dd HH:mm:ss.SSS";
    if (loggerContext == null) {
        LOGGER.error("Unknown loggerContext, aborting buffered logging. Make sure that loadFile() has been called first.");
        return;
    }
    // Build iterator
    Iterators<Appender<ILoggingEvent>> iterators = new Iterators<>();
    // Add CacheLogger or rootLogger appenders depending on whether CacheLogger is active.
    if (CacheLogger.isActive()) {
        iterators.addIterator(CacheLogger.iteratorForAppenders());
    } else {
        iterators.addIterator(rootLogger.iteratorForAppenders());
    }
    // If syslog is active there probably are detached appenders there as well
    if (!syslogDetachedAppenders.isEmpty()) {
        iterators.addList(syslogDetachedAppenders);
    }
    // Iterate
    Iterator<Appender<ILoggingEvent>> it = iterators.combinedIterator();
    while (it.hasNext()) {
        Appender<ILoggingEvent> appender = it.next();
        if (appender instanceof OutputStreamAppender && !(appender instanceof ConsoleAppender<?>)) {
            // Appender has Encoder property
            Encoder<ILoggingEvent> encoder = ((OutputStreamAppender<ILoggingEvent>) appender).getEncoder();
            if (encoder instanceof PatternLayoutEncoder) {
                // Encoder has pattern
                PatternLayoutEncoder patternEncoder = (PatternLayoutEncoder) encoder;
                String logPattern = patternEncoder.getPattern();
                // Set timestamp format
                Pattern pattern = Pattern.compile("%((date|d)(\\{([^\\}]*)\\})?)(?=\\s)");
                Matcher matcher = pattern.matcher(logPattern);
                if (matcher.find()) {
                    boolean replace = true;
                    if (matcher.group(4) != null && matcher.group(4).equals(timeStampFormat)) {
                        replace = false;
                    }
                    if (replace) {
                        logPattern = logPattern.replaceFirst(pattern.pattern(), "%d{" + timeStampFormat + "}");
                    }
                } else {
                    if (logPattern.startsWith("%-5level")) {
                        logPattern = logPattern.substring(0, 8) + " %d{" + timeStampFormat + "}" + logPattern.substring(8);
                    } else {
                        logPattern = "d%{" + timeStampFormat + "} " + logPattern;
                    }
                }
                // Make sure %logger is included
                pattern = Pattern.compile("((%logger|%lo|%c)(\\{\\d+\\})?)(?=\\s)");
                matcher = pattern.matcher(logPattern);
                if (matcher.find()) {
                    boolean replace = true;
                    if (matcher.group().equals("%logger")) {
                        replace = false;
                    }
                    if (replace) {
                        logPattern = logPattern.replaceFirst(pattern.pattern(), "%logger");
                    }
                } else {
                    if (logPattern.contains("%msg")) {
                        logPattern = logPattern.substring(0, logPattern.indexOf("%msg")) + "%logger " + logPattern.substring(logPattern.indexOf("%msg"));
                    } else {
                        logPattern = "%logger " + logPattern;
                    }
                }
                // Activate changes
                patternEncoder.setPattern(logPattern);
                patternEncoder.start();
            }
        }
    }
    LOGGER.info("Verbose file logging pattern enforced");
}
Also used : ConsoleAppender(ch.qos.logback.core.ConsoleAppender) OutputStreamAppender(ch.qos.logback.core.OutputStreamAppender) FileAppender(ch.qos.logback.core.FileAppender) SyslogAppender(ch.qos.logback.classic.net.SyslogAppender) Appender(ch.qos.logback.core.Appender) PatternLayoutEncoder(ch.qos.logback.classic.encoder.PatternLayoutEncoder) Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher) OutputStreamAppender(ch.qos.logback.core.OutputStreamAppender) ILoggingEvent(ch.qos.logback.classic.spi.ILoggingEvent) Iterators(net.pms.util.Iterators)

Example 3 with OutputStreamAppender

use of ch.qos.logback.core.OutputStreamAppender in project solr-document-store by DBCDK.

the class AsyncJob method initLog.

/**
 * Set up logging for this class
 *
 * @param wesocketAppender Optional websocket appender to notify with log.
 * If undesired, null can safely be passed instead
 * @throws IOException in case of file errors
 */
final void initLog(AsyncJobWesocketAppender wesocketAppender) throws IOException {
    UUID uuid = UUID.randomUUID();
    this.id = uuid.toString();
    this.file = File.createTempFile("/tmp/async-", ".log");
    this.write = new FileOutputStream(file);
    this.read = new RandomAccessFile(file, "r");
    LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
    this.log = context.getLogger(id);
    log.setLevel(Level.DEBUG);
    this.appender = new OutputStreamAppender();
    appender.setName(id);
    appender.setContext(log.getLoggerContext());
    appender.setOutputStream(write);
    PatternLayoutEncoder encoder = new PatternLayoutEncoder();
    encoder.setContext(context);
    encoder.setPattern(getLogPattern() + "%msg%n%rEx");
    // Not really sure why this is nessecary appender.setEncoder should do that
    encoder.init(write);
    encoder.start();
    appender.setEncoder(encoder);
    appender.start();
    log.addAppender(appender);
    if (wesocketAppender != null) {
        // Setup notifier using websocket to push updates to frontend
        // this.wsAppender = new AsyncJobWesocketAppender(uuid,name,sessionHandler);
        this.wsAppender = wesocketAppender;
        wsAppender.setContext(log.getLoggerContext());
        wsAppender.start();
        log.addAppender(wsAppender);
    }
}
Also used : PatternLayoutEncoder(ch.qos.logback.classic.encoder.PatternLayoutEncoder) RandomAccessFile(java.io.RandomAccessFile) OutputStreamAppender(ch.qos.logback.core.OutputStreamAppender) FileOutputStream(java.io.FileOutputStream) UUID(java.util.UUID) LoggerContext(ch.qos.logback.classic.LoggerContext)

Example 4 with OutputStreamAppender

use of ch.qos.logback.core.OutputStreamAppender in project zookeeper by apache.

the class LoggerTestTool method getConsoleAppender.

private OutputStreamAppender<ILoggingEvent> getConsoleAppender(ByteArrayOutputStream os) {
    Logger rootLogger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME);
    Layout<ILoggingEvent> layout = ((LayoutWrappingEncoder<ILoggingEvent>) ((OutputStreamAppender<ILoggingEvent>) rootLogger.getAppender("CONSOLE")).getEncoder()).getLayout();
    OutputStreamAppender<ILoggingEvent> appender = new OutputStreamAppender<>();
    appender.setContext((LoggerContext) LoggerFactory.getILoggerFactory());
    appender.setOutputStream(os);
    appender.setLayout(layout);
    return appender;
}
Also used : OutputStreamAppender(ch.qos.logback.core.OutputStreamAppender) Logger(ch.qos.logback.classic.Logger) ILoggingEvent(ch.qos.logback.classic.spi.ILoggingEvent) LayoutWrappingEncoder(ch.qos.logback.core.encoder.LayoutWrappingEncoder)

Example 5 with OutputStreamAppender

use of ch.qos.logback.core.OutputStreamAppender in project sonarqube by SonarSource.

the class WebServerProcessLoggingTest method use_json_output.

@Test
public void use_json_output() {
    props.set("sonar.log.jsonOutput", "true");
    LoggerContext context = underTest.configure(props);
    Logger rootLogger = context.getLogger(ROOT_LOGGER_NAME);
    OutputStreamAppender appender = (OutputStreamAppender) rootLogger.getAppender("file_web");
    Encoder<ILoggingEvent> encoder = appender.getEncoder();
    assertThat(encoder).isInstanceOf(LayoutWrappingEncoder.class);
    assertThat(((LayoutWrappingEncoder) encoder).getLayout()).isInstanceOf(LogbackJsonLayout.class);
}
Also used : OutputStreamAppender(ch.qos.logback.core.OutputStreamAppender) Logger(ch.qos.logback.classic.Logger) ILoggingEvent(ch.qos.logback.classic.spi.ILoggingEvent) LayoutWrappingEncoder(ch.qos.logback.core.encoder.LayoutWrappingEncoder) LoggerContext(ch.qos.logback.classic.LoggerContext) Test(org.junit.Test)

Aggregations

OutputStreamAppender (ch.qos.logback.core.OutputStreamAppender)5 ILoggingEvent (ch.qos.logback.classic.spi.ILoggingEvent)4 Logger (ch.qos.logback.classic.Logger)3 LoggerContext (ch.qos.logback.classic.LoggerContext)3 PatternLayoutEncoder (ch.qos.logback.classic.encoder.PatternLayoutEncoder)3 SyslogAppender (ch.qos.logback.classic.net.SyslogAppender)2 Appender (ch.qos.logback.core.Appender)2 ConsoleAppender (ch.qos.logback.core.ConsoleAppender)2 FileAppender (ch.qos.logback.core.FileAppender)2 LayoutWrappingEncoder (ch.qos.logback.core.encoder.LayoutWrappingEncoder)2 Test (org.junit.Test)2 ThresholdFilter (ch.qos.logback.classic.filter.ThresholdFilter)1 Filter (ch.qos.logback.core.filter.Filter)1 File (java.io.File)1 FileOutputStream (java.io.FileOutputStream)1 RandomAccessFile (java.io.RandomAccessFile)1 Field (java.lang.reflect.Field)1 UUID (java.util.UUID)1 Matcher (java.util.regex.Matcher)1 Pattern (java.util.regex.Pattern)1