Logback 我希望在从未使用附加器时不创建文件。 [滚动文件附加器]

问题描述 投票:0回答:2

我正在为我的应用程序创建一个 logback-common 配置文件。 我在其中定义了一个 RollingFileAppender,它为我的所有应用程序在文件中生成相同的日志格式(如果我们需要的话)。 有时我想使用这个附加程序,有时则不想使用(例如,当我们测试时)。

因此,我们根据需要配置特定的 logback-{profile}.xml。 但是当我们不使用 FILE 附加程序时,文件就会被创建,但我不希望这样。

我有:

  • logback-common.xml >> 包含所有附加程序定义(FILE 和 COMMON) 应用一
  • resources/logback.xml >> 调用 logback-common 和 config/logback-{profile}.xml
  • resources/config/logback-{profile}.xml >> 具体的appli/profile logback配置。

要配置我们可以在 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>
spring spring-boot logback spring-logback fileappender
2个回答
2
投票

不是 logback 的核心功能,但有一些解决方法可以实现延迟文件初始化。

查看更多这里 Logback - 启动时不要创建空日志文件


0
投票

在 janino 库的帮助下,可能有一种方法可以实现这一目标。

步骤-

  1. 添加 janino 依赖项。示例 - 实现 'org.codehaus.janino:janino'
  2. 在 logback-common.xml 添加 if-then 条件,如下所示 -
<if condition='property("spring.profiles.active").equals("<your_profile>"'>
<then>
... declare the file appender here ...
</then>
</if>
© www.soinside.com 2019 - 2024. All rights reserved.