我正在为我的应用程序创建一个 logback-common 配置文件。 我在其中定义了一个 RollingFileAppender,它为我的所有应用程序在文件中生成相同的日志格式(如果我们需要的话)。 有时我想使用这个附加程序,有时则不想使用(例如,当我们测试时)。
因此,我们根据需要配置特定的 logback-{profile}.xml。 但是当我们不使用 FILE 附加程序时,文件就会被创建,但我不希望这样。
我有:
要配置我们可以在 logback-{profile}.xml 中进行
<root level="WARN">
<appender-ref ref="FILE"/> <!-- For File Log when we need it -->
<appender-ref ref="CONSOLE"/>
</root>
<root level="WARN">
<!-- <appender-ref ref="FILE"/> --> <!-- in comment when we do not need if > BUT create a empty file -->
<appender-ref ref="CONSOLE"/>
</root>
logback-common.xml
<included>
<!-- The FILE and ASYNC appenders are here as examples for a production
configuration -->
<appender name="FILE"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>log/${spring.application.name}.log</file>
<rollingPolicy
class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>
log/${spring.application.name}.%d{yyyy-MM-dd}.%i.log.zip
</fileNamePattern>
<maxHistory>90</maxHistory>
<maxFileSize>10MB</maxFileSize>
</rollingPolicy>
<encoder>
<charset>utf-8</charset>
<Pattern>%d %-5level [%thread] %logger{0}: %msg%n</Pattern>
</encoder>
</appender>
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>"%d{yyyy-MM-dd} [%thread] %-5level %45logger{45} - %msg%n"</pattern>
</encoder>
</appender>
</included>
logback.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true" packagingData="true">
<property name="spring_profiles_active" value="${spring.profiles.active}" />
<property resource="application.properties"/>
<include resource="config/log/logback-common.xml"/>
<include resource="config/log/logback-${spring_profiles_active}.xml"/>
</configuration>
不是 logback 的核心功能,但有一些解决方法可以实现延迟文件初始化。
查看更多这里 Logback - 启动时不要创建空日志文件
在 janino 库的帮助下,可能有一种方法可以实现这一目标。
步骤-
<if condition='property("spring.profiles.active").equals("<your_profile>"'>
<then>
... declare the file appender here ...
</then>
</if>