Search code examples
javaspringspring-bootlogback

How to separate logging by severity to different files using springboot and logback


Im trying to send different logs to different files using logback.

I have 2 appenders configured (Console, RollingFile) and i want all

  • INFO messages -> Console appender
  • TRACE messages -> RollingFile appender:

logback-spring.xml

<root level="error">
    <appender-ref ref="RollingFile" />
    <appender-ref ref="Console" />
</root>

<logger name="com.mypkg" level="trace" additivity="true">
    <appender-ref ref="RollingFile" />
</logger>

<logger name="com.mypkg" level="info" additivity="true">
    <appender-ref ref="Console" />
</logger>

The result of the above configuration has 2 problems :

  • all messages are duplicated (both appenders)
  • com.mypkg shows only INFO (not TRACE) ob both appenders

any idea what im doing wrong ? is there any default spring logback file the is somehow merged with this config in runtime (changing the additivity to false fix the duplication issue, but still no TRACE messages) ?

Thanks .


Solution

  • You can try logback filters. There is a filter called LevelFilter. The option to accept and ignore log level types is also available here.

    Example :

    <configuration>
      <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
          <level>INFO</level>
          <onMatch>ACCEPT</onMatch>
          <onMismatch>DENY</onMismatch>
        </filter>
        <encoder>
          <pattern>
            %-4relative [%thread] %-5level %logger{30} - %msg%n
          </pattern>
        </encoder>
      </appender>
      <root level="DEBUG">
        <appender-ref ref="CONSOLE" />
      </root>
    </configuration>
    

    More information is in the below logback documentation.

    https://logback.qos.ch/manual/filters.html#levelFilter