小编典典

spring boot,logback和logging.config属性

spring

我正在使用logback库在spring boot项目中实现日志记录。我想根据我的spring配置文件(属性“ spring.pofiles.active”)加载不同的日志记录配置文件。我有3个文件:logback-dev.xml,logback-inte.xml和logback-prod.xml。我正在使用Spring Boot版本1.2.2.RELEASE。

如你在Spring Boot文档中所读。它说:

可以通过在类路径中包括适当的库来激活各种日志记录系统,并通过在类路径的根目录中或在Spring Environment属性logging.config指定的位置中提供适当的配置文件来进一步自定义各种日志记录系统。(但是请注意,由于日志记录是在创建ApplicationContext之前初始化的,因此无法从Spring @Configuration文件中的@PropertySources控制日志记录。系统属性和常规的Spring Boot外部配置文件都可以正常工作。)

所以我试图在我的application.properties文件中设置’logging.config’属性:

logging.config=classpath:/logback-${spring.profiles.active}.xml

但是,当我启动应用程序时,未加载我的logback- {profile} .xml …

我认为日志记录是使用Spring Boot的所有项目都遇到的常见问题。我采用上述方法走上正确的路吗?我还有其他可行的解决方案,但我发现它们不那么优雅(在logback.xml文件或命令行属性中使用Janino进行条件解析)。


阅读 5920

收藏
2020-04-17

共1个答案

小编典典

我找到了解决方案,并且理解了为什么spring不使用application.properties文件中定义的’logging.config’属性。

解决方案和说明:

初始化日志记录时,spring boot仅查找classpath或环境变量。

我使用的解决方案是包括一个父logback.xml文件,该文件根据spring概要文件包含了正确的日志记录配置文件。

logback.xml:

<configuration>
    <include resource="logback-${spring.profiles.active}.xml"/>
</configuration>

logback- [profile] .xml(在本例中为logback-dev.xml):

<included>

    <!-- put your appenders -->
    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
    <!-- encoders are assigned the type
     ch.qos.logback.classic.encoder.PatternLayoutEncoder by default -->
       <encoder>
           <pattern>%d{ISO8601} %p %t %c{0}.%M - %m%n</pattern>
           <charset>utf8</charset>
        </encoder>
    </appender>

    <!-- put your loggers here -->
    <logger name="org.springframework.web" additivity="false" level="INFO">
        <appender-ref ref="CONSOLE" />
    </logger>

    <!-- put your root here -->
    <root level="warn">
        <appender-ref ref="CONSOLE" />
    </root>

</included>

注意: 启动应用程序时,必须在命令行参数中设置“ spring.profiles.active”。EG for JVM属性:-Dspring.profiles.active=dev

编辑(多个活动配置文件):为了避免出现多个文件,我们可以使用需要Janino依赖的条件处理(在此处进行设置),请参阅条件文档。使用此方法,我们还可以同时检查多个活动配置文件。EG(我没有测试此解决方案,因此如果无法解决,请发表评论):

<configuration>

    <if condition='"${spring.profiles.active}".contains("profile1")'>
        <then>
         <!-- do whatever you want for profile1 -->
        </then>
    </if>

    <if condition='"${spring.profiles.active}".contains("profile2")'>
        <then>
         <!-- do whatever you want for profile2 -->
        </then>
    </if>

    <!-- common config -->

</configuration>

有关条件处理的另一个示例,请参见javasenior答案。

2020-04-17