Spring boot : Profile based logging using logback


  • 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


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">
                <pattern>%date %level [%thread] %logger{10} [%file : %line] %msg%n</pattern>
    <springProfile name="prod">
        <appender name="FILE" class="ch.qos.logback.core.FileAppender">
                <pattern>%date %level [%thread] %logger{10} [%file : %line] %msg%n</pattern>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">

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

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

Step 3 – Add logback dependency in pom.xml file


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 *