Java DuplicateMessageFilter-class And Method Code Example

Here is an example of using the DuplicateMessageFilter 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.DuplicateMessageFilter;

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.setPattern("%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n");

        // Create a console appender
        ConsoleAppender<ILoggingEvent> appender = new ConsoleAppender<>();

        // Create a duplicate message filter
        DuplicateMessageFilter filter = new DuplicateMessageFilter();


        // Attach the appender to the root logger

        // Log some messages
        for (int i = 0; i < 10; i++) {
            rootLogger.warn("Warning message");

In this example, we follow the same process of creating LoggerContext,PatternLayoutEncoder, and ConsoleAppender as previous example but in this case we added a DuplicateMessageFilter to the appender. The DuplicateMessageFilter is a filter that prevents log messages that are identical to the previous one from being printed. We start the filter after adding it to the appender so it will only allow new message to be printed and not the identical one .

As you can see in the for loop, We logged 10 same Warning message with the help of filter it only print the first one, and supress the rest.

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