matanster matanster - 1 year ago 87
Java Question

How to avoid double logging with logback?

In my application, I would like to log some messages coming from my own code in a specific manner compared to all other messages being logged. However I am not sure how can I avoid them also being automatically logged to the logack root logger.

Using this configuration below, I would like to use code like follows (scala) so that I can log certain messages only to that logger.

val logger: Logger = LoggerFactory.getLogger("data-logger")

However in the configuration below, these messages get logged twice, i.e. they are logged also by the root logger. How can I avoid that? must I quite artificially use a different logging level to accomplish something like that with logback?


<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">

<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">

<appender name="ASYNC" class="ch.qos.logback.classic.AsyncAppender">
<!-- use discarding threshold of zero to avoid ignoring INFO level messages see docs -->
<appender-ref ref="FILE" />

<root level="info">
<appender-ref ref="STDOUT" />
<appender-ref ref="ASYNC" />

<logger name="data-logger" level="info">
<appender-ref ref="STDOUT" />
<appender-ref ref="ASYNC" />


Answer Source

Loggers are hierarchical, and any message sent to a logger will be sent to all its ancestors by default. You can disable this behavior by setting additivity=false. E.g.:

<logger name="data-logger" level="info" additivity="false">