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

bxgwgixi  于 2024-01-05  发布在  Spring
关注(0)|答案(2)|浏览(143)

我正在为我的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中进行配置

  1. <root level="WARN">
  2. <appender-ref ref="FILE"/> <!-- For File Log when we need it -->
  3. <appender-ref ref="CONSOLE"/>
  4. </root>
  5. <root level="WARN">
  6. <!-- <appender-ref ref="FILE"/> --> <!-- in comment when we do not need if > BUT create a empty file -->
  7. <appender-ref ref="CONSOLE"/>
  8. </root>

字符串
logback-common.xml

  1. <included>
  2. <!-- The FILE and ASYNC appenders are here as examples for a production
  3. configuration -->
  4. <appender name="FILE"
  5. class="ch.qos.logback.core.rolling.RollingFileAppender">
  6. <file>log/${spring.application.name}.log</file>
  7. <rollingPolicy
  8. class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
  9. <fileNamePattern>
  10. log/${spring.application.name}.%d{yyyy-MM-dd}.%i.log.zip
  11. </fileNamePattern>
  12. <maxHistory>90</maxHistory>
  13. <maxFileSize>10MB</maxFileSize>
  14. </rollingPolicy>
  15. <encoder>
  16. <charset>utf-8</charset>
  17. <Pattern>%d %-5level [%thread] %logger{0}: %msg%n</Pattern>
  18. </encoder>
  19. </appender>
  20. <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
  21. <encoder>
  22. <pattern>"%d{yyyy-MM-dd} [%thread] %-5level %45logger{45} - %msg%n"</pattern>
  23. </encoder>
  24. </appender>
  25. </included>


logback.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <configuration scan="true" packagingData="true">
  3. <property name="spring_profiles_active" value="${spring.profiles.active}" />
  4. <property resource="application.properties"/>
  5. <include resource="config/log/logback-common.xml"/>
  6. <include resource="config/log/logback-${spring_profiles_active}.xml"/>
  7. </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条件-

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

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

相关问题