eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – Summer Sale 2026 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

Course – Summer Sale 2026 – NPI (cat=Baeldung)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

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 &amp;&amp; in XML -->
    <expression>
        isNull("environment") &amp;&amp; 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.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Summer Sale 2026 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

Course – Summer Sale 2026 – NPI (All)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

eBook Jackson – NPI EA – 3 (cat = Jackson)