Logback Duplicate log messages
By:Roy.LiuLast updated:2019-08-18
Review a simple Java application and log a message via Logback.
App.java
package com.mkyong.test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class App { private static final Logger log = LoggerFactory.getLogger(App.class); public static void main(String[] args) { log.debug("Testing");
P.S Tested with Logback 1.1.2
1. Problem
A simple logback.xml to log a message to console.
logback.xml
<?xml version="1.0" encoding="UTF-8"?> <configuration> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <layout class="ch.qos.logback.classic.PatternLayout"> <Pattern> %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n </Pattern> </layout> </appender> <logger name="com.mkyong.test" level="debug"> <appender-ref ref="STDOUT" /> </logger> <root level="error"> <appender-ref ref="STDOUT" /> </root> </configuration>
Run above program, the Logback will logs a message twice?
2015-01-25 13:55:21 [main] DEBUG com.mkyong.test.App - Testing 2015-01-25 13:55:21 [main] DEBUG com.mkyong.test.App - Testing
2. Solution
This is caused by the Appenders accumulate. To fix it, add a additivity="false" to the application logger
logback.xml
<logger name="com.mkyong.test" level="debug" additivity="false"> <appender-ref ref="STDOUT" /> </logger> <root level="error"> <appender-ref ref="STDOUT" /> </root>
Output
2015-01-25 13:58:24 [main] DEBUG com.mkyong.test.App - Testing
References
From:一号门
Previous:Spring @PropertySource example
COMMENTS