Search in sources :

Example 1 with ThresholdFilter

use of ch.qos.logback.classic.filter.ThresholdFilter in project google-cloud-java by GoogleCloudPlatform.

the class LoggingAppenderTest method testFilterLogsOnlyLogsAtOrAboveLogLevel.

@Test
public void testFilterLogsOnlyLogsAtOrAboveLogLevel() {
    LogEntry logEntry = LogEntry.newBuilder(StringPayload.of("this is a test")).setTimestamp(100000L).setSeverity(Severity.ERROR).setLabels(new ImmutableMap.Builder<String, String>().put("levelName", "ERROR").put("levelValue", String.valueOf(40000L)).build()).build();
    logging.setFlushSeverity(Severity.ERROR);
    Capture<Iterable<LogEntry>> capturedArgument = Capture.newInstance();
    logging.write(capture(capturedArgument), (WriteOption) anyObject(), (WriteOption) anyObject());
    expectLastCall().once();
    replay(logging);
    Timestamp timestamp = Timestamp.ofTimeSecondsAndNanos(100000, 0);
    LoggingEvent loggingEvent1 = createLoggingEvent(Level.INFO, timestamp.getSeconds());
    ThresholdFilter thresholdFilter = new ThresholdFilter();
    thresholdFilter.setLevel("ERROR");
    thresholdFilter.start();
    loggingAppender.addFilter(thresholdFilter);
    loggingAppender.start();
    // info event does not get logged
    loggingAppender.doAppend(loggingEvent1);
    LoggingEvent loggingEvent2 = createLoggingEvent(Level.ERROR, timestamp.getSeconds());
    // error event gets logged
    loggingAppender.doAppend(loggingEvent2);
    verify(logging);
    Assert.assertTrue(capturedArgument.getValue().iterator().hasNext());
    Assert.assertTrue(logEntry.equals(capturedArgument.getValue().iterator().next()));
}
Also used : LoggingEvent(ch.qos.logback.classic.spi.LoggingEvent) ThresholdFilter(ch.qos.logback.classic.filter.ThresholdFilter) Timestamp(com.google.cloud.Timestamp) LogEntry(com.google.cloud.logging.LogEntry) ImmutableMap(com.google.common.collect.ImmutableMap) Test(org.junit.Test)

Example 2 with ThresholdFilter

use of ch.qos.logback.classic.filter.ThresholdFilter in project Terasology by MovingBlocks.

the class TelemetryLogstashAppender method addErrorFilter.

private void addErrorFilter() {
    ThresholdFilter filter = new ThresholdFilter();
    filter.setLevel("error");
    filter.start();
    this.addFilter(filter);
}
Also used : ThresholdFilter(ch.qos.logback.classic.filter.ThresholdFilter)

Example 3 with ThresholdFilter

use of ch.qos.logback.classic.filter.ThresholdFilter 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 4 with ThresholdFilter

use of ch.qos.logback.classic.filter.ThresholdFilter in project UniversalMediaServer by UniversalMediaServer.

the class LoggingConfig method setConfigurableFilters.

private static synchronized void setConfigurableFilters(boolean setConsole, boolean setTraces) {
    PmsConfiguration configuration = PMS.getConfiguration();
    if (loggerContext == null) {
        LOGGER.error("Unknown loggerContext, aborting buffered logging. Make sure that loadFile() has been called first.");
        return;
    }
    if (setConsole) {
        Level level = configuration.getLoggingFilterConsole();
        if (consoleLevel == null || consoleLevel != level) {
            consoleLevel = level;
        } else {
            setConsole = false;
        }
    }
    if (setTraces) {
        Level level = configuration.getLoggingFilterLogsTab();
        if (tracesLevel == null || tracesLevel != level) {
            tracesLevel = level;
        } else {
            setTraces = false;
        }
    }
    if (setConsole || setTraces) {
        // Since Console- and FrameAppender will exist at root level and won't be detached by syslog,
        // there's no reason to build an iterator as this should suffice.
        Iterator<Appender<ILoggingEvent>> it = CacheLogger.isActive() ? CacheLogger.iteratorForAppenders() : rootLogger.iteratorForAppenders();
        while (it.hasNext()) {
            Appender<ILoggingEvent> appender = it.next();
            if (setConsole && appender instanceof ConsoleAppender) {
                ConsoleAppender<ILoggingEvent> ca = (ConsoleAppender<ILoggingEvent>) appender;
                boolean createNew = true;
                if (!ca.getCopyOfAttachedFiltersList().isEmpty()) {
                    for (Filter<ILoggingEvent> filter : ca.getCopyOfAttachedFiltersList()) {
                        if (filter instanceof ThresholdFilter) {
                            createNew = false;
                            ((ThresholdFilter) filter).setLevel(consoleLevel.levelStr);
                            ((ThresholdFilter) filter).start();
                        }
                    }
                }
                if (createNew) {
                    ThresholdFilter consoleFilter = new ThresholdFilter();
                    ca.addFilter(consoleFilter);
                    consoleFilter.setLevel(consoleLevel.levelStr);
                    consoleFilter.setContext(loggerContext);
                    consoleFilter.start();
                }
            }
            if (setTraces && appender instanceof FrameAppender) {
                FrameAppender<ILoggingEvent> fa = (FrameAppender<ILoggingEvent>) appender;
                boolean createNew = true;
                if (!fa.getCopyOfAttachedFiltersList().isEmpty()) {
                    for (Filter<ILoggingEvent> filter : fa.getCopyOfAttachedFiltersList()) {
                        if (filter instanceof ThresholdFilter) {
                            createNew = false;
                            ((ThresholdFilter) filter).setLevel(tracesLevel.levelStr);
                            ((ThresholdFilter) filter).start();
                        }
                    }
                }
                if (createNew) {
                    ThresholdFilter tracesFilter = new ThresholdFilter();
                    fa.addFilter(tracesFilter);
                    tracesFilter.setLevel(tracesLevel.levelStr);
                    tracesFilter.setContext(loggerContext);
                    tracesFilter.start();
                }
            }
        }
    }
}
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) ConsoleAppender(ch.qos.logback.core.ConsoleAppender) ThresholdFilter(ch.qos.logback.classic.filter.ThresholdFilter) ILoggingEvent(ch.qos.logback.classic.spi.ILoggingEvent) PmsConfiguration(net.pms.configuration.PmsConfiguration) Level(ch.qos.logback.classic.Level)

Example 5 with ThresholdFilter

use of ch.qos.logback.classic.filter.ThresholdFilter in project FredBoat by Frederikam.

the class SentryConfiguration method getSentryLogbackAppender.

// programmatically creates a sentry appender
private static synchronized SentryAppender getSentryLogbackAppender() {
    LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
    ch.qos.logback.classic.Logger root = loggerContext.getLogger(Logger.ROOT_LOGGER_NAME);
    SentryAppender sentryAppender = (SentryAppender) root.getAppender(SENTRY_APPENDER_NAME);
    if (sentryAppender == null) {
        sentryAppender = new SentryAppender();
        sentryAppender.setName(SENTRY_APPENDER_NAME);
        ThresholdFilter warningsOrAboveFilter = new ThresholdFilter();
        warningsOrAboveFilter.setLevel(Level.WARN.levelStr);
        warningsOrAboveFilter.start();
        sentryAppender.addFilter(warningsOrAboveFilter);
        sentryAppender.setContext(loggerContext);
        root.addAppender(sentryAppender);
    }
    return sentryAppender;
}
Also used : ThresholdFilter(ch.qos.logback.classic.filter.ThresholdFilter) SentryAppender(io.sentry.logback.SentryAppender) LoggerContext(ch.qos.logback.classic.LoggerContext)

Aggregations

ThresholdFilter (ch.qos.logback.classic.filter.ThresholdFilter)14 ILoggingEvent (ch.qos.logback.classic.spi.ILoggingEvent)5 ConsoleAppender (ch.qos.logback.core.ConsoleAppender)5 LoggerContext (ch.qos.logback.classic.LoggerContext)4 Test (org.junit.Test)4 Logger (ch.qos.logback.classic.Logger)3 Appender (ch.qos.logback.core.Appender)3 Level (ch.qos.logback.classic.Level)2 SyslogAppender (ch.qos.logback.classic.net.SyslogAppender)2 FileAppender (ch.qos.logback.core.FileAppender)2 OutputStreamAppender (ch.qos.logback.core.OutputStreamAppender)2 LayoutWrappingEncoder (ch.qos.logback.core.encoder.LayoutWrappingEncoder)2 SentryAppender (io.sentry.logback.SentryAppender)2 Field (java.lang.reflect.Field)2 PmsConfiguration (net.pms.configuration.PmsConfiguration)2 PatternLayoutEncoder (ch.qos.logback.classic.encoder.PatternLayoutEncoder)1 JoranConfigurator (ch.qos.logback.classic.joran.JoranConfigurator)1 LoggingEvent (ch.qos.logback.classic.spi.LoggingEvent)1 Filter (ch.qos.logback.core.filter.Filter)1 JoranException (ch.qos.logback.core.joran.spi.JoranException)1