Spring Boot Logback with Profile

Farzin Pashaee
2 min readJun 24, 2022

Logging is a very important part of each application we will refer them to monitor and debug in different environments. But each environment might have different requirements. You may need different levels of logging in production compared to the development or testing environment. Spring Boot with Logback provides a simple yet useful solution for this approach. If you want to know more about Logging in Spring Boot you can refer to this article:

Getting Start

To begin with, you need to follow some naming syntax on the Logback configuration file. Change the default logback.xml file to logback-spring.xml. By doing this Spring Boot will know that you are going to use some Spring-related tags in the configuration file.

The base structure of the logback-spring.xml configuration is the same as a normal Logback configuration file. You will have Appenders and Loggers to define your logging rules. The only new tags, in this case, will be the springProfile tag that will wrap around the loggers to have different setups for different environments.

<springProfile name="prod">
<!-- enabled when the "prod" profile is active -->
</springProfile>
<springProfile name="dev | test">
<!-- enabled when the "dev" or "test" profiles are active --></springProfile>
<springProfile name="!prod">
<!-- enabled when the "prod" profile is not active --></springProfile>

As you can see in the examples there are also some logical operands that you can use to have a combinational or exceptional configuration. “|” will let you simulate “OR” and “!” will mimic the exception.

<?xml version="1.0" encoding="UTF-8"?><configuration><include resource="org/springframework/boot/logging/logback/console-appender.xml" /><appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">  <encoder>
<pattern>${FILE_LOG_PATTERN}</pattern>
</encoder>
<file>temp/spring.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"
<fileNamePattern>temp/spring.log.%d</fileNamePattern>
</rollingPolicy>
</appender>
<springProfile name="test | dev">
<logger
name="fp.spring" level="DEBUG" additivity="false">
<appender-ref
ref="CONSOLE" />
</logger>
<root level="DEBUG">
<appender-ref
ref="CONSOLE" />
<appender-ref
ref="FILE" />
</root>
</springProfile>
<springProfile name="prod">
<root
level="INFO">
<appender-ref
ref="FILE" />
</root>
</springProfile>
</configuration>

In the above example, you can see how we utilized the <springProfile> tag to manage levels and loggers based on our deployed environment. if you are not familiar with how to set the profile in your application please refer to this article:

Hope this article helped you and please support me with your applauding 👏 for the story. if you don’t know how it is just like this:

Or buy me a coffee here!

--

--