有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java SLF4JLogback:基于日志级别的多模式

使用Logback是因为我们需要一些log4j没有提供的appender

要求:对于日志级错误,我们希望使用自定义模式,该模式将根据堆栈跟踪添加信息

对于所有其他日志级别,它应该使用简单模式

所有日志输出都应该放在同一个文件中

尝试了以下内容:创建了两个附加器,一个用于错误日志级别,另一个用于其他日志级别。 当两个附加器使用相同的目标文件时,错误日志不会写入该文件。 当两个附加器使用不同的目标文件时,将创建两个文件,一个具有错误日志级别,另一个具有所有其他日志级别

使用log4j2找到了一些指针,但使用logback目前无法找到解决方案

有人能提出一些建议吗


共 (2) 个答案

  1. # 1 楼答案

    在appender配置中,将prudentive设置为true。这将允许多个appender写入同一个文件

  2. # 2 楼答案

    从Prasanth Nair那里找到答案。在logback https://logback.qos.ch/manual/appenders.html手册中,您可以找到

    In prudent mode, FileAppender will safely write to the specified file, even in the presence of other FileAppender instances running in different JVMs, potentially running on different hosts. The default value for prudent mode is false.

    下面是一个配置示例:

    <configuration>
      <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <!  Support multiple-JVM writing to the same log file  >
        <prudent>true</prudent>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
          <fileNamePattern>logFile.%d{yyyy-MM-dd}.log</fileNamePattern>
          <maxHistory>30</maxHistory> 
          <totalSizeCap>3GB</totalSizeCap>
        </rollingPolicy>
    
        <encoder>
          <pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n</pattern>
        </encoder>
      </appender> 
    
      <root level="DEBUG">
        <appender-ref ref="FILE" />
      </root>
    </configuration>