matanster matanster - 5 months ago 29
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?

<configuration>

<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>logs/activity.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
<fileNamePattern>activity.%i.log.zip</fileNamePattern>
<minIndex>1</minIndex>
<maxIndex>10</maxIndex>
</rollingPolicy>
<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<maxFileSize>10MB</maxFileSize>
</triggeringPolicy>
<encoder>
<pattern>%msg%n</pattern>
</encoder>
</appender>

<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%msg%n</pattern>
</encoder>
</appender>

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

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

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

</configuration>

Answer

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">