spring Logback我想在appender从未使用时不创建文件,[RollingFileAppender]

bxgwgixi  于 5个月前  发布在  Spring
关注(0)|答案(2)|浏览(42)

我正在为我的applis创建一个logback公共配置文件。我在其中定义了一个RollingFileAppender,它为我所有的applis在一个文件中生成相同的日志格式(如果我们需要它)。有时我想使用这个appender,有时不想(例如当我们测试时)。
因此,我们根据需要配置特定的logback-{profile}.xml。但当我们不使用FILE appender时,文件会被创建,而我不希望这样。
我有:

  • logback-common.xml >>包含所有appenders定义(FILE和COMMON)appli_one
  • 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>

nhn9ugyo

nhn9ugyo1#

这不是logback的核心特性,但有一些解决方法可以实现延迟文件初始化。
查看更多Logback - do not create empty log files at startup

uqcuzwp8

uqcuzwp82#

在janino图书馆的帮助下,可能有一种方法可以实现这一点。
步骤-
1.添加janino依赖项。示例-实现'org.codehaus.janino:janino'
1.在logback-common.xml中添加如下所示的if-then条件-

<if condition='property("spring.profiles.active").equals("<your_profile>"'>
<then>
... declare the file appender here ...
</then>
</if>

字符串
友情链接:https:logback.qos.ch/codes.html#nested_if_element

相关问题