Search code examples
javalogginglogbackspring-logback

How to use different fileName patterns based on the lifecycle environment


How to use different versions of logback.xml based on the active spring boot profile

src/main/resources/logback.xml
src/main/resources/logback-qa.xml
src/main/resources/logback-staging.xml
src/main/resources/logback-production.xml

My intention is to change the fileNamePattern alone based on the environment as well as the file path, I would prefer not to created additional files, if its easier to achieve it with a single file

<fileNamePattern>logs/app.%d{yyyy-MM-dd}.log</fileNamePattern>
<fileNamePattern>logs/app-qa.%d{yyyy-MM-dd}.log</fileNamePattern>
<fileNamePattern>logs/app-staging.%d{yyyy-MM-dd}.log</fileNamePattern>
<fileNamePattern>/logs/app-production.%d{yyyy-MM-dd}.log</fileNamePattern>

Solution

  • logback-spring.xml supports springProfile tag and Spring Boot recommends to use logback-spring.xml instead of logback.xml. You can use springProfile tag in logback-spring.xml as follows:

    <springProfile name="staging">
        <!-- configuration to be enabled when the "staging" profile is active -->
    </springProfile>
    
    <springProfile name="dev | staging">
        <!-- configuration to be enabled when the "dev" or "staging" profiles are active -->
    </springProfile>
    
    <springProfile name="!production">
        <!-- configuration to be enabled when the "production" profile is not active -->
    </springProfile>