Logback multi-Environment configuration and logback environment Configuration
Currently, most projects need to differentiate test and development among other environments. Therefore, maven, spring, and other projects all have features such as profile, and different configurations can be used for different environments. therefore, logs may need different configurations based on different environments. the log file needs to be differentiated from the environment, so it searches for relevant information and finds that logback does provide such support.
Find a description of the <if> label configuration in the logback official documentation. It provides a function to determine whether to output the configuration based on the expression value, similar to the if, examples on the official website are as follows:
<!-- if-then form --> <if condition="some conditional expression"> <then> ... </then> </if> <!-- if-then-else form --> <if condition="some conditional expression"> <then> ... </then> <else> ... </else> </if>
This <if> label can be used anywhere inside the <configuration> label in the log configuration file. A simple example is as follows:
<?xml version="1.0" encoding="UTF-8"?><configuration> <property resource="config.properties" /> <appender name="stdout" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <charset>UTF-8</charset> <pattern>%date [%thread] %-5level - %msg%n</pattern> </encoder> </appender> <if condition='property("logstash").contains("true")'> <then> <appender name="logStash" class="net.logstash.logback.appender.LogstashTcpSocketAppender"> <destination>${logstash.address}</destination> <encoder class="net.logstash.logback.encoder.LogstashEncoder" /> <keepAliveDuration>15 minutes</keepAliveDuration> </appender> </then> </if> <root level="ERROR"> <appender-ref ref="stdout"/> <if condition='property("logstash").contains("true")'> <then> <appender-ref ref="logStash"/> </then> </if> </root></configuration>
This type of tag only supports values from the property, or from the system property, which is a string type value. You can use the contains method to determine whether a condition is met.
Note: This is implemented through the Janino library, so you need to add the dependencies of this library.
<dependency> <groupId>org.codehaus.janino</groupId> <artifactId>janino</artifactId> <version>3.0.6</version></dependency>