Defining 1 logback file per level [duplicate]

2019-03-31 01:30发布

问题:

This question already has an answer here:

  • How can I configure Logback to log different levels for a logger to different destinations? 12 answers

I'd like to define a logback configuration file that will be able to :

  • log DEBUG (and higher) things in debug.log
  • log INFO (and higher) things in info.log

That is to say, when I call :

logger.warn("blah"); // Logs to both info.log and debug.log
logger.debug("bleh"); // Logs to debug.log only

Is it possible ?

I tried something like this, but it seems like when logback encounters multiple <root> tags, it only takes the last one :

<appender name="infoFile" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <File>${LOGS_FOLDER}/info.log</File>
    <encoder>
        <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
    </encoder>
</appender>
<appender name="debugFile" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <File>${LOGS_FOLDER}/debug.log</File>
    <encoder>
        <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
    </encoder>
</appender>

<root level="INFO">
  <appender-ref ref="infoFile" />
</root>
<root level="DEBUG">
  <appender-ref ref="debugFile" />
</root>

Here, info.log contains debug-level logs :(

Note that I want to apply this behaviour on every of my packages.

回答1:

Using a levelFilter solved the problem

Example :

<appender name="infoFile" class="ch.qos.logback.core.rolling.RollingFileAppender">
  <File>${LOGS_FOLDER}/info.log</File>
  <filter class="ch.qos.logback.classic.filter.LevelFilter">
    <level>INFO</level>
    <onMatch>ACCEPT</onMatch>
    <onMismatch>DENY</onMismatch>
  </filter>
  <encoder>
    <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
  </encoder>
</appender>
<appender name="debugFile" class="ch.qos.logback.core.rolling.RollingFileAppender">
  <File>${LOGS_FOLDER}/debug.log</File>
  <encoder>
    <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
  </encoder>
</appender>

<root level="DEBUG"><!-- Using the lowest level here -->
  <appender-ref ref="debugFile" />
  <appender-ref ref="infoFile" />
</root>