Java DynamicThresholdFilter-class And Method Code Example


Here is an example of using the DynamicThresholdFilter class from the logback.classic.filter package in Java:

import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
import ch.qos.logback.core.ConsoleAppender;
import ch.qos.logback.core.filter.DynamicThresholdFilter;

public class Example {
    public static void main(String[] args) {
        LoggerContext context = new LoggerContext();
        Logger rootLogger = context.getLogger(Logger.ROOT_LOGGER_NAME);

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

        // Create a console appender
        ConsoleAppender<ILoggingEvent> appender = new ConsoleAppender<>();
        appender.setContext(context);
        appender.setEncoder(encoder);

        // Create a dynamic threshold filter
        DynamicThresholdFilter filter = new DynamicThresholdFilter();
        filter.setContext(context);
        filter.setKey("userId");
        filter.setDefaultThreshold(Level.ERROR);
        filter.start();
        appender.addFilter(filter);

        appender.start();

        // Attach the appender to the root logger
        rootLogger.addAppender(appender);

        // Log some messages
        MDC.put("userId", "user1");
        rootLogger.debug("Debug message");
        rootLogger.info("Info message");
        rootLogger.warn("Warning message");
        rootLogger.error("Error message");
        
        MDC.put("userId", "user2");
        rootLogger.debug("Debug message");
        rootLogger.info("Info message");
        rootLogger.warn("Warning message");
        rootLogger.error("Error message");
        
        MDC.clear();
    }
}

In this example, We create DynamicThresholdFilter and set the key value userId , the filter will check for this key value in MDC (Mapped Diagnostic Context) and assign the threshold based on this key value. We also set the default threshold level for this filter as ERROR. With this, we can set different threshold levels for different users.

As you can see in the example, We set the MDC with key userId as user1 and user2 before each log statement, so it will assign the threshold level based on that key value.

Note that you need to add logback classic and slf4j-ext library in the classpath to use this example.