Profile Based Logging with Spring Boot

Posted By : Anil Kumar Maurya | 31-Oct-2018

Logging is one of the most concern to developers while developing the application. Spring boot provides multiples ways to achieve it. By using spring boot starter dependencies, we can achieve only basic logging and cannot configure if more complex logging is required. For the simpler alterations, they can be added to a properties file, such as application.properties or for more complex needs, you can use XML or Groovy to specify your settings.

I will explain the XML configuration to achieve the profile based logging. For the XML based logging configuration, we can create a logback.xml file and put it somewhere in our classpath. Now we can configure logback.xml file according to our logging requirement. A simple logback.xml file will look like-

 

<configuration>
  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <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>


Many times, we need different logging configurations for different profiles that we are using in our application. There are two ways to achieve this type of logging-

 

1. By using springProfile property tag-

If we don't need much different or slightly different logging for every profile then we can do this configuration in a single XML file. Name this file as logback-spring.xml, it's spring boot standard naming convention. Inside the logback-spring.xml file, we define below configurations for different profiles-

 

<configuration>
  <springProfile name="dev">
    ...
  </springProfile>
  <springProfile name="stag,prod">
    ...
  </springProfile>
</configuration>


2. By creating separate XML files-

If we have significant differences in logging requirement for different profiles then we can create a separate XML file for every profile. The naming convention should be like logback-{profile}.xml. For example, if we are using dev profile create logback-dev.xml, or for staging profile create logback-stag.xml etc. Now we can provide our own configuration as per the requirement.

 

 

 

 

About Author

Author Image
Anil Kumar Maurya

Anil is an experienced Lead with core knowledge of Java, Spring, and SQL. He has good working experience in banking, finance and trading domain.

Request for Proposal

Name is required

Comment is required

Sending message..