I am using Logback to do most of my logging. I am using a third party library for some computation. Luckily the library uses slf4j, meaning it’s agnostic of the logging implementation.

The library caches two collections of items and depending on the circumstances the item I am looking for may be in any of the two collections. This is not important. What is important, is that the library for some reason logs an error if an item cannot be found in the first collection.

I wanted to get rid of this message because it was cluttering my logs. But I didn’t want to disable all logging from this specific class, because it may print some useful logs. I just wanted to get rid of this specific log. There is a way to do it using an evaluator.

My logback.xml looks like the following:

<configuration scan="true" scanPeriod="30 seconds" debug="false">

	<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
		<layout class="ch.qos.logback.classic.PatternLayout">
			<pattern>%date{dd MMM yyyy HH:mm:ss.SSS} [%thread] %-5level %class -
				%msg%n</pattern>
		</layout>
		<filter class="ch.qos.logback.core.filter.EvaluatorFilter">
			<evaluator>
				<expression>return
					logger.contains("com.kgasoft.Logger1")
					&amp;&amp; (message.contains("Do not print")||
					throwable.getMessage().contains("Do not print Exception"));</expression>
			</evaluator>
			<OnMismatch>NEUTRAL</OnMismatch>
			<OnMatch>DENY</OnMatch>
		</filter>
	</appender>

	<root level="INFO">
		<appender-ref ref="STDOUT" />
	</root>

</configuration>

Then I use the following Unit Test and only one of the 3 messages is logged, as expected:

package com.kgasoft.examples.logback;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LogbackTest {

	private final Logger logger = LoggerFactory.getLogger("com.kgasoft.Logger1");
	
	
	@Test
	public void testWillPrint(){
		logger.error("This is an error message");
	}
	
	@Test
	public void testDoNotPrint1(){
		logger.error("Do not print this message");
	}
	
	@Test
	public void testDoNotPrint2(){
		logger.error("This message should not be print due to exception",new Exception("Do not print Exception error message"));
	}
}

One thought on “Do not Log Messages Using Logback

Leave a reply

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> 

required

Page last modified: 13:56 on January 22, 2019 (UTC+2)