Sub topic 15
Testing log output
This chapter shows how to assert on log output in automated tests, and when doing so is worth it. It assumes you can write JUnit 5 tests, you have spring-boot-starter-test on the test classpath, and you know how to write log statements with an SLF4J Logger (covered earlier in this tutorial).
Deciding whether to test logs
Most log lines do not need a test. A debug message that says "Processing order" is a diagnostic aid, and a test that pins its exact wording makes refactoring harder without protecting any behavior.
Test log output when the log line is part of a contract:
- An audit or security line that operators or compliance rules depend on, such as a failed login or a permission change.
- A warning or error that an alert rule matches by text or by level.
- A guarantee that something is not logged, such as a password or token.
- Error handling, where you want to confirm the exception was logged with its stack trace and not swallowed.
For these cases, assert on the level and the message template or arguments. Avoid asserting on the full formatted line, because the timestamp, thread name, and pattern come from configuration and change often.
Choosing a technique
Spring Boot gives you two main ways to observe logs in a test, and there is a third option for configuring what gets logged.
| Technique | What you assert on | Best for |
|---|---|---|
| `OutputCaptureExtension` | The text written to the console | Quick checks that a message appeared or did not appear |
| Logback `ListAppender` | Structured events: level, message, arguments, exception, MDC | Precise checks on level, arguments, and stack traces |
| Test-specific configuration | Nothing, it controls what is logged | Setting levels with `@SpringBootTest(properties = ...)` or a `logback-test.xml` file |
Capturing console output
OutputCaptureExtension is a JUnit 5 extension that ships in spring-boot-starter-test. It records everything written to System.out and System.err during a test and injects it as a CapturedOutput parameter. Because Logback's console appender writes to those streams, the log lines show up in the captured text.
The tests below use the OrderService from the chapter on writing log statements.
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
@ExtendWith(OutputCaptureExtension.class)
class OrderServiceOutputTest {
private final OrderService service = new OrderService();
@Test
void placeOrderLogsOrderIdAndItemCount(CapturedOutput output) {
service.placeOrder("A-100", 3);
assertThat(output).contains("Placing order A-100 with 3 items");
}
}CapturedOutput implements CharSequence, so AssertJ's string assertions work on it directly. It also has getOut(), getErr(), and getAll() methods when you need to separate the two streams.
This approach has limits you should know about:
- Levels depend on the setup. In a plain unit test with no Spring context, Spring Boot's logging system is not initialized, and Logback falls back to its default configuration, which logs at DEBUG to the console. In a
@SpringBootTest, yourapplication.propertieslevels apply, so adebugline may disappear. - The text depends on the pattern. A custom
logging.pattern.consolechanges what you capture. Assert on the message fragment, not the whole line. - Parallel tests can interleave. If tests run in parallel, output from other threads can land in your capture. Assert with
contains, not equality, or use aListAppender.
Inspecting events with a ListAppender
A ListAppender is a Logback class that stores each log event in a list instead of writing it anywhere. You attach it to a specific logger, run the code, and inspect the events as objects. This lets you check the level, the unformatted template, the arguments, and the exception without parsing text.
This API belongs to Logback, not SLF4J, so you must cast the SLF4J logger to Logback's Logger. That cast only works when Logback is the active backend. If you switched to Log4j2, use that library's own test appenders instead.
Here is a small service to test:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
@Service
public class PaymentService {
private static final Logger log = LoggerFactory.getLogger(PaymentService.class);
public void charge(String orderId, int cents) {
if (cents <= 0) {
log.warn("Rejected charge for order {}: amount {}", orderId, cents);
throw new IllegalArgumentException("amount must be positive");
}
log.info("Charged order {}", orderId);
}
}And the test:
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.read.ListAppender;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.slf4j.LoggerFactory;
class PaymentServiceLogTest {
private final Logger logger = (Logger) LoggerFactory.getLogger(PaymentService.class);
private final ListAppender<ILoggingEvent> appender = new ListAppender<>();
private final PaymentService service = new PaymentService();
@BeforeEach
void attachAppender() {
appender.start();
logger.addAppender(appender);
}
@AfterEach
void detachAppender() {
logger.detachAppender(appender);
appender.stop();
}
@Test
void rejectedChargeLogsWarningWithArguments() {
assertThatThrownBy(() -> service.charge("A-1", 0))
.isInstanceOf(IllegalArgumentException.class);
assertThat(appender.list).hasSize(1);
ILoggingEvent event = appender.list.get(0);
assertThat(event.getLevel()).isEqualTo(Level.WARN);
assertThat(event.getMessage())
.isEqualTo("Rejected charge for order {}: amount {}");
assertThat(event.getArgumentArray()).containsExactly("A-1", 0);
}
}Three details matter here:
- Start the appender before you attach it, and detach it afterwards. Loggers are shared across the whole JVM. If you leave the appender attached, it collects events from later tests and can make them fail in confusing ways.
getMessage()returns the template, andgetFormattedMessage()returns the filled-in text. Asserting on the template withgetArgumentArray()keeps the test stable even if you change how values are rendered.- Events exist only if the level allows them. If the effective level of the logger is higher than the event's level, no event is created and the list stays empty. In a test that must see debug output, set the level on the logger first with
logger.setLevel(Level.DEBUG), and restore the previous level in@AfterEach.
Checking exceptions and MDC values
An ILoggingEvent carries more than the message. When you log an exception as the last argument, as OrderService does with log.error("Order {} failed", orderId, ex), the event holds it:
ILoggingEvent event = appender.list.get(0);
assertThat(event.getThrowableProxy()).isNotNull();
assertThat(event.getThrowableProxy().getClassName())
.isEqualTo("java.lang.IllegalStateException");If the stack trace is missing, the usual cause is that the exception was concatenated into the message or passed with ex.getMessage(). A test like this catches that mistake.
To verify context from the MDC (the per-thread map of values, such as requestId, that the log pattern can print), read event.getMDCPropertyMap(). The map is copied when the event is created. A test can therefore confirm that a filter set requestId before the log call, even though the filter removes it afterwards.
Controlling levels in Spring Boot tests
When a test loads the application context, you can set log levels for just that test class without editing application.properties:
@SpringBootTest(properties = "logging.level.com.example.orders=debug")
class OrderFlowTest {
// debug lines from com.example.orders are visible here
}Properties set this way go through the same mechanism as the property-based configuration covered earlier, so the logger names and level names behave the same. For a different setup across all tests, put a logback-test.xml in src/test/resources. Logback looks for that file name before logback.xml, so it overrides your main configuration during test runs only.
Common mistakes
- Forgetting to detach a
ListAppender, so later tests see extra events. - Asserting on the full console line, which breaks whenever someone edits the pattern.
- Expecting debug output in a
@SpringBootTestwhenapplication.propertiessets the level higher. - Casting to Logback's
Loggerafter switching the backend to Log4j2, which throws aClassCastException. - Testing every log line, which turns wording changes into test failures with no real regression behind them.
Exercise
A test attaches a ListAppender to the logger for PaymentService, calls charge("A-1", 5), and expects one INFO event. The list is empty. The test class is a @SpringBootTest and application.properties contains logging.level.root=warn. What is the most likely cause, and how can you fix it in the test?
Show answer
The effective level of the PaymentService logger is WARN, inherited from the root logger, so the INFO call produces no event and the appender never sees it. Fix it by setting the level for that logger in the test, either with @SpringBootTest(properties = "logging.level.com.example.PaymentService=info") (using the real package name) or by calling logger.setLevel(Level.INFO) in @BeforeEach and restoring the old level in @AfterEach.
Exercise
Why is asserting event.getMessage() equal to the template plus event.getArgumentArray() usually more stable than asserting on the console line captured by OutputCaptureExtension?
Show answer
The template and arguments do not depend on the log pattern, timestamp, thread name, or color settings, and they are not affected by interleaved output from other threads. The captured console line includes all of those, so a pattern change or parallel test can break it even when the logged message is correct.