Sub topic 15
Testing log output
This chapter assumes you can write JUnit 5 tests, use AssertJ, and have spring-boot-starter-test on the test classpath. It also assumes you know the OrderService class from the chapter on writing log statements.
Why test logs at all
Most log lines don't need tests. Test a log line when something else depends on it. Examples are an audit entry, an alert rule that matches an error message, or a rule that a password must never appear in the output. Do not assert on every debug call, because those tests break whenever someone rewords a message.
Two approaches
| Approach | What it checks | Good for |
|---|---|---|
| `OutputCaptureExtension` | Text written to the console | Quick checks of message text |
| Logback `ListAppender` | Structured events: level, message, arguments, exception | Checking levels and exceptions |
Capturing console output
Spring Boot's OutputCaptureExtension records what is written to System.out and System.err. JUnit passes the recorded text to the test as a CapturedOutput parameter.
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 {
@Test
void logsOrderPlacement(CapturedOutput output) {
new OrderService().placeOrder("A-1", 3);
assertThat(output).contains("Placing order A-1 with 3 items");
}
}The assertion sees the formatted line, so it also depends on the console pattern and the active level.
Inspecting events with a ListAppender
A ListAppender is a Logback appender that keeps events in a list instead of writing them anywhere. You attach it to one logger, run the code, and read the events. Because you cast to Logback's Logger, this approach only works while Logback is the backend.
import static org.assertj.core.api.Assertions.assertThat;
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 OrderServiceEventsTest {
private Logger logger;
private Level originalLevel;
private ListAppender<ILoggingEvent> appender;
@BeforeEach
void attachAppender() {
logger = (Logger) LoggerFactory.getLogger(OrderService.class);
originalLevel = logger.getLevel();
logger.setLevel(Level.DEBUG);
appender = new ListAppender<>();
appender.start();
logger.addAppender(appender);
}
@AfterEach
void detachAppender() {
logger.detachAppender(appender);
logger.setLevel(originalLevel);
}
@Test
void logsInfoThenDebug() {
new OrderService().placeOrder("A-1", 3);
assertThat(appender.list).hasSize(2);
assertThat(appender.list.get(0).getLevel()).isEqualTo(Level.INFO);
assertThat(appender.list.get(0).getFormattedMessage())
.isEqualTo("Placing order A-1 with 3 items");
assertThat(appender.list.get(1).getLevel()).isEqualTo(Level.DEBUG);
}
}For a logged exception, call getThrowableProxy() on the event. It returns null when no exception was passed.
Common errors
- Debug lines are missing. The default root level is
INFO. Raise the level for the logger under test, as theListAppendertest does, or setlogging.level.com.example.orders=debugin test properties. - Asserting on the raw message template.
getMessage()returnsPlacing order {} with {} items. UsegetFormattedMessage()for the final text. - Fragile console assertions. Matching a whole line couples the test to the timestamp and pattern. Use
containson the message text only.
Exercise
Why can getMessage() and getFormattedMessage() return different strings on the same ILoggingEvent, and which one should a test normally assert on?
Show answer
getMessage() returns the template with {} placeholders, while getFormattedMessage() returns the text with the arguments substituted. A test should normally assert on getFormattedMessage(), because that is the text a reader sees in the log.
Exercise
A test using OutputCaptureExtension expects a debug line but fails, even though the message text is correct. What is the most likely cause?
Show answer
The logger's effective level is INFO or higher, so the debug statement never produced output. Set the level for that package to debug in the test configuration.