简体   繁体   中英

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

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?

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

Spring will only pickup profile information in your logback config when naming your config file " logback-spring.xml " instead of "logback.xml".

Inside the config file you can simply use your profiles like this example:

 <springProfile name="sst">
     <appender-ref ref="JSON_STDOUT"/>
     ...
 </springProfile>

You can even use negation for your profiles:

 <springProfile name="!prod">
     <appender-ref ref="JSON_STDOUT"/>
     ...
 </springProfile>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM