Main Tutorials

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 Author

author image
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

Subscribe
Notify of
7 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Ivan
6 years ago

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
6 years ago

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

Karan Mehta
4 years ago

This is producing multiple logs: logback.xml

[%X{key}][%X{user}]%date{“yyyy-MM-dd’T’HH:mm:ss,SSSXXX”, Asia/Jakarta} %-5level
%logger{35} – %replace(%msg){‘\n’, ‘ ‘}%nopex%n

Please help.

David Newcomb
4 years ago

How can I delete my comment?

Serdar Kuzucu
5 years ago

God bless you mkyong!

Jack X Peng
7 years ago

You already have additivity=false in 1.problem.

mkyong
7 years ago
Reply to  Jack X Peng

fixed, thanks.