How to Write a Custom Logback Filter in Micronaut

Logback is a widely used logging framework in the Java ecosystem. It provides flexibility and configurability for logging messages generated in your application. In Micronaut, you can easily integrate Logback for your logging needs. Sometimes, you may want to apply custom filtering to log messages, allowing you to control which messages get logged and which ones don’t. In this blog post, we’ll explore how to write a custom Logback filter in Micronaut.

Understanding Logback Filters

Logback filters allow you to decide whether a log event should be passed on to the next filter or the final destination, such as a file or console. Filters are evaluated in a chain, and each filter can accept, deny, or neutralize an event. If a filter denies an event, it will not propagate further down the chain.

To write a custom Logback filter, you need to implement the ch.qos.logback.core.filter.Filter interface and override the decide method. The decide method is where you define your custom logic to determine whether an event should be allowed or denied.

Creating a Custom Logback Filter

Let’s create a custom Logback filter that logs only messages with a specific keyword in them. Here’s a step-by-step guide:

Step 1: Add Dependency to build.gradle file

Add logback dependency in build.gradle file if the library is not present.

dependencies {
....
implementation("ch.qos.logback:logback-classic")
}

Step 2: Create a Custom Filter Class

Create a Java or Kotlin class that implements the ch.qos.logback.core.filter.Filter interface. For this example, let’s name it KeywordFilter.

package com.example.common

import ch.qos.logback.classic.spi.ILoggingEvent
import ch.qos.logback.core.spi.FilterReply


class CustomLogbackFilter : ch.qos.logback.core.filter.Filter<ILoggingEvent?>() {

    override fun decide(event: ILoggingEvent?): FilterReply? {
        return if (event?.getMessage()?.contains("Dummy") == true) {
            FilterReply.DENY
        } else {
            FilterReply.ACCEPT
        }
    }
}

In this filter, we check if the log message contains the ‘Dummy’ Keyword. If it does, we deny the event; otherwise, we accept it.

Step 3: Configure Logback

Now, configure Logback in your Micronaut project to use this custom filter. Create or modify the logback.xml or logback-spring.xml configuration file in your project’s resources directory. Add the custom filter like this:

<configuration>

    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <filter class="com.example.common.CustomLogbackFilter"> </filter>
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <root level="debug">
        <appender-ref ref="STDOUT" />
    </root>

</configuration>

Step 3: Using the Custom Filter

Now that your custom filter is configured, you can use it in your Micronaut application. Whenever you log a message containing the ‘Dummy’ Keyword, it will be denied; otherwise, it will be get logged.

log.error(“This Dummy Event got trigger during Startup”)
log.error(“This Event got trigger during Startup”)

Implementation: https://github.com/cw-bhanunadar/Micronaut-playground/pull/6/files

That’s it! You’ve successfully created and used a custom Logback filter in your Micronaut application. Custom filters provide you with fine-grained control over which log messages get recorded, allowing you to tailor your logging to your specific needs.

Conclusion

Logback is a powerful logging framework, and Micronaut makes it easy to integrate and customize it for your applications. By creating custom Logback filters, you can enhance your logging capabilities and gain more control over which log messages are captured. Whether you want to filter messages by keywords, severity, or any other criteria, Logback’s flexibility and custom filters have you covered.

Related Post