logback.xml中读取application-{profile}.properties日志路径配置

一、首先,了解profile

Spring Boot 允许你通过命名约定按照一定的格式 (application-{profile}.properties) 来定义多个配置文件,然后通过在 application.properties 通过 spring.profiles.active 来具体激活一个或者多个配置文件,如果没有指定任何 profile 的配置文件,Spring Boot 默认会启动 application-default.properties。

1.1 具体配置实现方法参考如下

在 application.properties 文件的同路径下,创建不同的环境参数文件,命名格式为:application-{profile}.properties,其中 {profile} 对应环境标识。

如上图所示,项目共配置了三个不同的环境,分别为:

  1. application-dev.properties:开发环境
  2. application-test.properties:测试环境
  3. application-prod.properties:生产环境

      至于哪个具体的配置文件会被加载,需要在 application.properties 文件中通过spring.profiles.active 属性来设置,其值对应 {profile} 值。

修改 application.properties 文件内容,指定生效的环境,内容如下。
        spring.profiles.active=dev
spring.profiles.active 取值可为 dev、prod、test。上述配置指定开发环境配置文件有效,即取 application-dev.properties 文件中的相关配置。

1.2 启动脚本

启动时指定生效的 profiles 参数,启动脚本示例如下所示。
nohup java -Xms3g -Xmx3g -Xmn1g -Xss256k -XX:+PrintGCDetails -XX:+PrintGCDateStamps -Xloggc:/logdisk/gclog/gctest.log -jar test-1.0-SNAPSHOT.jar --spring.profiles.active=prod  >/dev/null 2>&1 &

二、配置配置加载顺序

最先加载的是application.properties,logback.xml的加载晚于application.properties,所以logback.xml可以读到application.properties里面配置的值。
logback.xml的加载要先于application.yml,所以直接通过${参数key}的形式获取是无法获取到application.yml对应参数值的。

注:

亲测,即使是在 application.properties里,直接写:

<property name="logging.path" source="logging.path"/> 也不行的,

需要写成:

<springProperty scope="context" name="logging.path" source="logging.path"/>

Environment Properties:

Core Featureshttps://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.logging.logback-extensions.environment-properties

       The <springProperty> tag lets you expose properties from the Spring Environment for use within Logback. Doing so can be useful if you want to access values from your application.properties file in your Logback configuration. The tag works in a similar way to Logback’s standard <property> tag.

        However, rather than specifying a direct value, you specify the source of the property (from the Environment). If you need to store the property somewhere other than in local scope, you can use the scope attribute. If you need a fallback value (in case the property is not set in the Environment), you can use the defaultValue attribute. The following example shows how to expose properties for use within Logback:

翻译:

      该 <springProperty> 标签允许我们从Spring中显示属性,Environment 以便在Logback中使用。如果你想将 application.properties在回读配置中访问文件中的值,这将非常有用。

      标签的工作方式与Logback的标准 <property> 标签类似,但不是直接value 指定source属性(从Environment)指定。scope 如果需要将属性存储在local范围之外的其他位置,则可以使用该属性。如果您需要一个后备值,以防该属性未设置,则Environment可以使用该defaultValue属性。

例子1:

<springProperty scope="context" name="fluentHost" source="myapp.fluentd.host"
        defaultValue="localhost"/>
<appender name="FLUENT" class="ch.qos.logback.more.appenders.DataFluentAppender">
    <remoteHost>${fluentHost}</remoteHost>
    ...
</appender>

例子2 :

<!-- 读取spring.application.name中的属性来生成日志文件名 -->
<springProperty scope="context" name="logName" source="spring.application.name" defaultValue="localhost.log"/>

<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>logs/${logName}.log</file>    <!-- 使用方法 -->
    <append>true</append>
    <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
        <fileNamePattern>logs/${logName}-%d{yyyy-MM-dd}.%i.log.zip</fileNamePattern>
        <maxFileSize>100MB</maxFileSize>
        <maxHistory>7</maxHistory>
        <totalSizeCap>3GB</totalSizeCap>
    </rollingPolicy>
    <encoder>
        <pattern>[%date{yyyy-MM-dd HH:mm:ss}] [%-5level] [%logger:%line] --%mdc{client} %msg%n</pattern>
    </encoder>
    <filter class="ch.qos.logback.classic.filter.LevelFilter">
        <level>DEBUG</level>
    </filter>
</appender>

注意: 

The source must be specified in kebab case (such as my.property-name). However, properties can be added to the Environment by using the relaxed rules.

三、配置 logback.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" scanPeriod="10 seconds">

    <!-- 日志输出路径: logging.path 在application.properties中配置,注意下面是 springProperty 不是 property -->
    <springProperty scope="context" name="logging.path" source="logging.path"/>
    <!-- 日志输出格式 -->
    <property name="log.pattern" value="%d{YY-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{20} - [%method,%line] - %msg%n" />

    <include resource="org/springframework/boot/logging/logback/base.xml"/>
    <contextName>logback</contextName>
   

    <!-- 系统日志输出 -->
    <appender name="file_info" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${logging.path}/sys-info.log</file>
        <!-- 循环政策:基于时间创建日志文件 -->
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!-- 日志文件名格式 -->
            <fileNamePattern>${logging.path}/sys-info.%d{yyyy-MM-dd}.log</fileNamePattern>
            <!-- 日志最大的历史 60天 -->
            <maxHistory>60</maxHistory>
        </rollingPolicy>
        <encoder>
            <pattern>${log.pattern}</pattern>
        </encoder>
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <!-- 过滤的级别 -->
            <level>INFO</level>
            <!-- 匹配时的操作:接收(记录) -->
            <onMatch>ACCEPT</onMatch>
            <!-- 不匹配时的操作:拒绝(不记录) -->
            <onMismatch>DENY</onMismatch>
        </filter>
    </appender>

    <appender name="file_error" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${logging.path}/sys-error.log</file>
        <!-- 循环政策:基于时间创建日志文件 -->
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!-- 日志文件名格式 -->
            <fileNamePattern>${logging.path}/sys-error.%d{yyyy-MM-dd}.log</fileNamePattern>
            <!-- 日志最大的历史 60天 -->
            <maxHistory>60</maxHistory>
        </rollingPolicy>
        <encoder>
            <pattern>${log.pattern}</pattern>
        </encoder>
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <!-- 过滤的级别 -->
            <level>ERROR</level>
            <!-- 匹配时的操作:接收(记录) -->
            <onMatch>ACCEPT</onMatch>
            <!-- 不匹配时的操作:拒绝(不记录) -->
            <onMismatch>DENY</onMismatch>
        </filter>
    </appender>

    <root level="INFO">
        <appender-ref ref="CONSOLE"/>
        <!-- 添加本地日志记录 -->
        <appender-ref ref="file_info" />
        <appender-ref ref="file_error" />
    </root>
    <logger name="org.apache.flume.sink.LoggerSink" additivity="false">
        <level value="INFO"/>
    </logger>
</configuration>

在项目 application-{profile}.properties 中添加自定义路径设置

# 自定义日志输出文件所在文件夹路径
logging.path=/Volumes/F/testLog

四、参考:

logback.xml中读取application.properties日志路径配置 - 知乎


版权声明:本文为yangyangye原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。