Search code examples
logback

logback - remapping a log level for a specific logger


I have a logback configuration that has an appender with a threshold filter:

<appender name="SYSLOG" class="ch.qos.logback.classic.net.SyslogAppender">
  <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
    <level>INFO</level>
  </filter>
  ...
</appender>

This ensures that only info and higher (warn, error) get logged to syslog. However, one of the 3rd party libraries we use is logging a particular event at DEBUG, and I would like to log this event to syslog. The first approach I had in mind was to try remap the log level in the logger, but am not sure if this is possible? Something like:

<logger name="akka.some.Thing" level="DEBUG" logAs="INFO">
  <appender-ref ref="SYSLOG" />
</logger>

obviously, the "logAs" parameter doesn't exist, so I can't do that. What would be the best approach to logging akka.some.Thing to the SYSLOG appender while leaving the filter in place for other loggers?

The other approach would be to create a 2nd appender called SYSLOG2 that doesn't have the filter in place and set the specific logger to use that, but was wondering if there was a way to configure logback with just 1 SYSLOG appender...

Thanks,


Solution

  • Take a look at the org.springframework.boot.logging.logback.LevelRemappingAppender class. (Note that it's been removed from Sprint Boot, but you can still grab and use its source code.) With this appender it is possible to both remap what appender is finally used for the log event, and it is also possible to remap the level that is used for the final log event - e.g. by changing a DEBUG level into an INFO level.

    Example logback.xml:

    <appender name="DEBUG_LEVEL_REMAPPER" class="org.springframework.boot.logging.logback.LevelRemappingAppender">
        <!-- Optional: specify the destination logger the event ends up in -->
        <destinationLogger>org.springframework.boot</destinationLogger>
        <!-- Optional: specify log level remapping  -->
        <remapLevels>INFO->DEBUG,ERROR->WARN</remapLevels>
    </appender>
    
    <logger name="org.thymeleaf" additivity="false">
        <appender-ref ref="DEBUG_LEVEL_REMAPPER"/>
    </logger>
    

    Note that remapping to a specific destination logger can make it harder to find the source code of the original log event - so use it with care.