Spring Boot: How to use custom logback.xml depending on current environment or spring profile

Nestor Milyaev :

I have read the following two sources:

https://examples.javacodegeeks.com/enterprise-java/spring/load-environment-configurations-and-properties-with-spring-example/

spring-boot logback.xml property depending on profile

And I'm trying to do the following:

When I run my Spring Boot application with a specific spring active profile (gradlew bootRun -Dspring.profiles.active=sst, which we use for single service tests), I need the application use specific logging configuration (let's say with specific log level or using logging that we could capture output of from the tests).

We do have a custom application-sst.properties file configured and that is picked up and works all right.

Is there a way for me to do something similar for the logback.xml - such as adding logback-sst.xml so that is used within the SST context?

Mark Bramnik :

Some suggestions:

  1. If you need something a special configuration for tests only, there is a simple solution: Place logback-test.xml in src/test/resources and you're good to go.

  2. Logback supports a concept of spring profiles that allow placing configurations for different profiles in the same file:

Example:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>

<springProfile name="dev">
   <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
   ... 
  </appender>

  <root level="DEBUG">
    <appender-ref ref="CONSOLE"/>
  </root>
</springProfile>

<springProfile name="staging">
    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
     ...
    </appender>

    <root level="DEBUG">
      <appender-ref ref="CONSOLE"/>
    </root>
</springProfile>

</configuration>

Here you can find the relevant tutorial

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=329476&siteId=1