这是indexloc提供的服务,不要输入任何密码
Skip to content
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>