Spring boot : Profile based logging using logback

Summary:

  • Logging using logback in Springboot application
  • How to add profile based configuration in logback-spring.xml (logback.xml) file

In Spring boot application, you can create different profiles to have environment specific configuration. This could be used for having different database urls, host names, environment configurations etc. Similar to these configuration, you can configure different environment specific logging configuration in logback.

Step 1 – Add different profiles in pom.xml file

org.springframework.boot
spring-boot-maven-plugin
1.5.7.RELEASE

dev prod

Step 2 – Create logback-spring.xml file and add profile based configuration. In below snippet, tag is used to have different appenders for dev and prod profile

<configuration debug="true">

    <springProfile name="dev">
        <appender name="FILE" class="ch.qos.logback.core.FileAppender">
            <file>/Users/xyz/logs/logback-dev.log</file>
            <encoder>
                <pattern>%date %level [%thread] %logger{10} [%file : %line] %msg%n</pattern>
            </encoder>
        </appender>
    </springProfile>
    <springProfile name="prod">
        <appender name="FILE" class="ch.qos.logback.core.FileAppender">
            <file>/Users/xyz/logs/logback-prod.log</file>
            <encoder>
                <pattern>%date %level [%thread] %logger{10} [%file : %line] %msg%n</pattern>
            </encoder>
        </appender>
    </springProfile>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%msg%n</pattern>
        </encoder>
    </appender>

    <logger name="com.test" additivity="true">
        <appender-ref ref="FILE" />
    </logger>

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

Step 3 – Add logback dependency in pom.xml file

<dependency>
  <groupId>ch.qos.logback</groupId>
  <artifactId>logback-classic</artifactId>
  <version>1.2.3</version>
</dependency>



Step 4 – Add LOG statements in java code
Something like –

package com.test;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TestLogback {

    private static final Logger LOGGER =  LoggerFactory.getLogger(TestLogback.class);

    public void testLog() {
        LOGGER.info("In test log method");
    }
}

Step 5 – Run spring boot application by providing profile name as VM argument
Following two java runtime configurations will generate different log files based on profile-
java -Dspring.profiles.active=prod -jar springBootDemo.jar
java -Dspring.profiles.active=dev -jar springBootDemo.jar




Leave a Reply

Your email address will not be published. Required fields are marked *