logback多環境配置,logback環境配置
現在項目基本都是要區分測試開發等等一系列環境的,也因此maven,spring之類的都具有profile這類功能,可以針對不同的環境採用不同的配置.因此日誌也可能根據不同的環境需要不同的配置.恰巧手頭上碰到了這麼一個需求,記錄檔也需要區分環境,便搜尋了一下相關的資料,發現logback的確也提供這麼一種支援.
從logback官網的文檔中找到一段關於<if>標籤的配置說明,它提供一種根據運算式的值來決定是否輸出配置的功能,類似於c標籤中的if,官網的樣本如下:
<!-- 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>
這個<if>標籤可以使用在日誌設定檔中的<configuration>標籤內部任意位置,一種簡單的使用執行個體如下:
<?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>
這種標籤只支援從property中取值,或是從system系統property中取值,取出的為string類型的值,可以通過contains方法判斷是否滿足某個條件.
特別說明:這個是通過Janino庫實現的,故需要加入此庫的依賴.
<dependency> <groupId>org.codehaus.janino</groupId> <artifactId>janino</artifactId> <version>3.0.6</version></dependency>