当前位置: 移动技术网 > IT编程>开发语言>Java > logback多环境配置

logback多环境配置

2018年01月20日  | 移动技术网IT编程  | 我要评论

现在项目基本都是要区分测试开发等等一系列环境的,也因此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>

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网