Logback – Duplicate log messages

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

  1. Logback Configuration

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
5 Comment threads
1 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
6 Comment authors
David NewcombSerdar KuzucuIvanCody Burlesonmkyong Recent comment authors
newest oldest most voted
Ivan
Guest
Ivan

You don’t need to set additivity = false
Just remove STDOUT appender from com.mkyong.test logger
So it will be

logger com.mkyong.test without additivity = false will inherit all ancestors appenders
In this case com.mkyong.test has only one ancestor (root) will inherit STDOUT from root and successfully log into STDOUT with level DEBUG (from com.mkyong.test package)

Cody Burleson
Guest
Cody Burleson

What would Java developers do without you, man? You’ve saved me so much time on so much crap. Thank you!!!

Jack X Peng
Guest
Jack X Peng

You already have additivity=false in 1.problem.

Serdar Kuzucu
Guest
Serdar Kuzucu

God bless you mkyong!

David Newcomb
Guest
David Newcomb

How can I delete my comment?