Dynamically set per-request log level using logback filters

Ravinder Thirumala
2 min readAug 26, 2021

Logging is a fundamental part of any application, It benefits not only for developers but also to support teams and business people equally. Logging Frameworks allows us to specify log levels so that the application can be easily configured to just log messages that are marked as the specified log level or with lower level.

Changing Log Level of an application to DEBUG for a given request and then capturing contextual data in the logs for that request will greatly benefit for debugging.

In this article we will implement sample API using SpringBoot and see how to enable DEBUG level logging for the API flow by specifying Log Level in Http header.

Basically we are enabling DEBUG Level logging for the API by setting header as seen below.

curl -H “set-Log-Level:DEBUG” http://localhost:8080/example

With the above API call, debug log level is set for the request flow in the application.

Now we will see how this can be achived in out SpringBoot application, We already know that Spring Boot framework is preconfigured with Logback as a default implementation. Logback logging framework have a capability called Filters which allow to associate Log level to a key put in the MDC. we will be using DynamicThresholdFilter for course grained filtering based on criteria.

This filter will allow us to associate Log level to a key put in the MDC (Mapped Diagnostic Context), Key…

--

--