Let's get started with a Microservice Architecture with Spring Cloud:
Conditional Logging With Logback
Last updated: May 6, 2026
1. Overview
The Logback logging framework is a successor to the Log4j project, providing unique, flexible, and advanced features that are not found in other logging systems. One such feature is conditional logging, which enables us to control the log output. This is useful when we have different use cases at runtime that require redirecting, controlling, or suppressing logs.
In this tutorial, we’ll look into some interesting features the Logback framework provides for conditional logging.
2. Setup
Logback requires the Simple Logging Facade for Java (SLF4J) library as a dependency. However, as SLF4J is the reference implementation of Logback, we don’t need to import it explicitly. Importing the logback-classic library automatically pulls slf4j-api.jar and logback-core.jar into the project through Maven’s transitive dependency rules.
So, let’s add the Logback library to our POM:
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.5.24</version>
</dependency>
Moreover, conditional processing in Logback configuration files requires the Janino library. Janino is an embedded Java compiler that can compile Java code or expressions dynamically at run-time. Let’s add it to our POM:
<dependency>
<groupId>org.codehaus.janino</groupId>
<artifactId>janino</artifactId>
<version>3.1.12</version>
</dependency>
We can get more recent versions of the logback-classic and janino dependencies from Maven Central.
3. Conditional Processing of Configuration Files
Conditional processing of configuration files allows us to control configuration behavior based on specific conditions. This can be useful to filter the logs dynamically based on certain runtime scenarios.
Logback supports conditional logging through conditional processing of configuration files. Instead of embedding Java expressions directly inside the <if> element, recent versions use a <condition> element to define the condition, followed by an <if> block that executes based on that condition.
3.1. General Format
Let’s see the general format for using conditional statements:
<condition class="ch.qos.logback.core.boolex.PropertyEqualityCondition">
<key>ENVIRONMENT</key>
<value>PROD</value>
</condition>
<if>
<then>
...
</then>
</if>
In addition, Logback supports if-then-else blocks too:
<condition class="ch.qos.logback.core.boolex.PropertyEqualityCondition">
<key>ENVIRONMENT</key>
<value>PROD</value>
</condition>
<if>
<then>
...
</then>
<else>
...
</else>
</if>
Since 1.5.20, the <condition> element precedes the <if>,<then>, and <else> elements. Conditional processing using the <condition> element was introduced in Logback version 1.5.20.
If the <condition> evaluates to true, the <then> part is activated; if false, the <else> part is activated, if present.
Conditional processing can be used anywhere within the <configuration> element, and nested if-then-else statements are also supported. However, conditionals should be used sparingly.
3.2. Conditional Logging With System or Context Properties
To access a specific system or context property, we now use condition classes instead of inline property() expressions.
For instance, to activate configuration when the property with the key “ENVIRONMENT” has a value “PROD“, we can write:
<condition class="ch.qos.logback.core.boolex.PropertyEqualityCondition">
<key>ENVIRONMENT</key>
<value>PROD</value>
</condition>
<if>
<then>
<appender name="FILE_APPENDER" class="ch.qos.logback.core.FileAppender">
<file>${outputDir}/conditional.log</file>
<encoder>
<pattern>%d %-5level %logger{35} -%kvp- %msg %n</pattern>
</encoder>
</appender>
</then>
</if>
Likewise, if we want to check whether a property is defined, we can use IsPropertyDefinedCondition:
<condition class="ch.qos.logback.core.boolex.IsPropertyDefinedCondition">
<key>ENVIRONMENT</key>
</condition>
<if>
<then>
<appender name="CONSOLE_APPENDER" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d %-5level %logger{35} -%kvp- %msg %n</pattern>
</encoder>
</appender>
</then>
</if>
Similarly, to enable Logstash only when LOG_STASH_URL is defined:
<condition class="ch.qos.logback.core.boolex.IsPropertyDefinedCondition">
<key>LOG_STASH_URL</key>
</condition>
<if>
<then>
<appender name="LOG_STASH_APPENDER" class="net.logstash.logback.appender.LogstashTcpSocketAppender">
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
<level>ERROR</level>
</filter>
<destination>${LOG_STASH_URL}</destination>
<encoder class="net.logstash.logback.encoder.LogstashEncoder">
<customFields>{"app_name": "TestApp"}</customFields>
</encoder>
</appender>
</then>
</if>
Logback supports conditional processing anywhere within the <configuration> root element.
3.3. Boolean Expression Conditions
In addition to simple property equality and defined checks, Logback (since version 1.5.24) supports evaluating full boolean expressions using ExpressionPropertyCondition.
This allows more advanced configuration logic using Java-like operators such as !, &&, and ||, along with parentheses for grouping expressions.
Several predefined helper functions are available:
- isDefined(“key”)
- isNull(“key”)
- propertyEquals(“key”, “value”)
- propertyContains(“key”, “value”)
As with other conditions, properties are resolved using Logback’s standard lookup order: local scope first, followed by context scope, then system properties, and finally OS environment variables.
For example, the following configuration enables a console appender if the environment property is null and the HOSTNAME property equals “torino”:
<condition class="ch.qos.logback.core.boolex.ExpressionPropertyCondition">
<!-- Note that && must be written as && in XML -->
<expression>
isNull("environment") && propertyEquals("HOSTNAME", "torino")
</expression>
</condition>
<if>
<then>
<appender name="CON" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d %-5level %logger{35} -%kvp- %msg %n</pattern>
</encoder>
</appender>
<root>
<appender-ref ref="CON" />
</root>
</then>
<else>
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
<file>${randomOutputDir}/conditional.log</file>
<encoder>
<pattern>%d %-5level %logger{35} -%kvp- %msg %n</pattern>
</encoder>
</appender>
<root level="ERROR">
<appender-ref ref="FILE" />
</root>
</else>
</if>
Using expression-based conditions is particularly useful when configuration behavior depends on multiple properties or more complex runtime scenarios.
4. Using EvaluatorFilter
Logback filters can be chained together to compose an arbitrarily complex filtering policy. These filters are based on ternary logic and return one of the DENY, NEUTRAL, or ACCEPT values.
Returning DENY would mean that the log event is dropped immediately. In the case of NEUTRAL, the next filter will be consulted. Finally, ACCEPT implies that the processing of the logging event is successful and skips the remaining filters.
Conditional logging can also be achieved using EvaluatorFilter. The OnMatch and OnMismatch tags provide options to return one of the three ternary values (DENY, NEUTRAL, or ACCEPT). Accordingly, this Logback filter can control the logs’ output.
4.1. Implement EventEvaluatorBase
First, we need to create a custom event evaluator, let’s say BillingMessageEvaluator, to classify messages about our billing system. We specify this in an EventEvaluatorBase subclass:
public class BillingMessageEvaluator extends EventEvaluatorBase<ILoggingEvent> {
@Override
public boolean evaluate(ILoggingEvent event) throws EvaluationException {
String message = event.getMessage();
return message.contains("billing");
}
}
This custom evaluator class evaluates logging events and returns true if a message contains the word “billing”.
4.2. Configure Logback Appender
Next, we need to configure Logback to use our evaluator and state what should happen when our evaluator matches a log. Since we want to filter out matching messages, we use <OnMatch>DENY</OnMatch>:
<configuration>
<appender name="FILTER_APPENDER" class="ch.qos.logback.core.FileAppender">
<file>filtered.log</file>
<filter class="ch.qos.logback.core.filter.EvaluatorFilter">
<evaluator class="com.baeldung.logback.BillingMessageEvaluator"/>
<OnMatch>DENY</OnMatch>
<OnMismatch>NEUTRAL</OnMismatch>
</filter>
<encoder>
<pattern>%d [%thread] %-5level %logger{36} -%kvp- %msg%n</pattern>
</encoder>
</appender>
<root level="DEBUG">
<appender-ref ref="FILTER_APPENDER" />
</root>
</configuration>
With this configuration, the EvaluatorFilter evaluates messages using our evaluator, blocks (DENY) any logs that match the condition, and otherwise allows other evaluators to weigh in (NEUTRAL).
4.3. Test With JUnit
Now let’s test this. We’ll create our logger and write one message that contains the word “billing” and one that doesn’t:
@Test
public void whenMatchedWithEvaluatorFilter_thenReturnFilteredLogs() throws IOException {
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"));
}
Because “billing details: XXXX” contains the word “billing”, we expect it not to be in the logs in the end.
5. Spring Profiles and Variable Substitutions
As seen above, Logback supports the conditional processing of configuration files and the EvaluatorFilter class to restrict log output. However, both these approaches require additional lines to the XML syntax. Subsequently, having too many conditionals may quickly render the configuration files unreadable and unmanageable in the long run.
However, there are alternative approaches to managing the logs natively. For Spring-based applications, we could use Spring Profiles, which is much cleaner than managing the logs using expressions or filters. For example, we can have logback-dev.xml for development, logback-staging.xml for staging, and logback-prod.xml for production environments.
Alternatively, we can use environment-specific variables to conditionally point to specific loggers at runtime. For instance, we can define the variable “ROOT_APPENDER” via the system property, so that the actual root appender will be chosen at runtime through variable substitution. This way, we can dynamically redirect logs to a designated output, which can be particularly useful for maintaining environment-specific appenders such as LogStash.
These approaches eliminate the need for multiple if-then-else blocks required for conditional processing or additional lines for evaluating expressions using the EvaluationFilter method.
6. Conclusion
In this article, we discussed the conditional logging features provided by the Logback framework. First, we looked at the conditional processing feature along with a few helpful utility methods to check the availability of a specific property. Next, we discussed the EvaluatorFilter, which uses a custom event evaluator to filter logs. Finally, we saw some alternatives to these features, where we can try Spring profiles or environment-specific variables to achieve the same result.
The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.

















