Skip to content

BAEL-9356 Update "Conditional Logging with logback" article #18661

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 11 commits into
base: master
Choose a base branch
from
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.baeldung.logback;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.boolex.EventEvaluatorBase;
import ch.qos.logback.core.boolex.EvaluationException;

public class BillingMessageEvaluator extends EventEvaluatorBase<ILoggingEvent> {

@Override
public boolean evaluate(ILoggingEvent event) throws NullPointerException, EvaluationException {
String message = event.getMessage();
return message.contains("billing");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -47,4 +47,16 @@ public void whenSystemPropertyIsPresent_thenReturnFileLogger() throws IOExceptio
String logOutput = FileUtils.readFileToString(new File("conditional.log"));
assertTrue(logOutput.contains("test prod log"));
}

@Test
public void whenMatchedWithEvaluatorFilter_thenReturnFilteredLogs() throws IOException {
System.setProperty("ENVIRONMENT", "PROD");
logger = (Logger) LoggerFactory.getLogger(ConditionalLoggingUnitTest.class);
logger.info("billing details: XXXX");
logger.info("test prod log");

String filteredLog = FileUtils.readFileToString(new File("filtered.log"));
assertTrue(filteredLog.contains("test prod log"));
assertFalse(filteredLog.contains("billing details: XXXX"));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -38,15 +38,13 @@
<appender name="FILTER_APPENDER" class="ch.qos.logback.core.FileAppender">
<file>filtered.log</file>
<filter class="ch.qos.logback.core.filter.EvaluatorFilter">
<evaluator>
<expression>return message.contains("billing");</expression>
</evaluator>
<evaluator class="com.baeldung.logback.BillingMessageEvaluator"/>
<OnMatch>DENY</OnMatch>
<OnMismatch>NEUTRAL</OnMismatch>
</filter>
<encoder>
<pattern>%d %-4relative [%thread] %-5level %logger -%kvp -%msg%n</pattern>
</encoder>
<layout>
<pattern>%d [%thread] %-5level %logger{36} -%kvp- %msg%n</pattern>
</layout>
</appender>

<appender name="CONSOLE_APPENDER" class="ch.qos.logback.core.ConsoleAppender">
Expand All @@ -60,4 +58,4 @@
<appender-ref ref="FILTER_APPENDER" />
<appender-ref ref="CONSOLE_APPENDER" />
</root>
</configuration>
</configuration>