Testing Java logging filters and appenders in unit tests
Logging is the one part of a Java service that every team depends on and almost nobody tests. Filters and appenders look like plumbing, yet they encode rules that matter: keep card numbers out of a file appender, route audit events to their own destination, silence a chatty third-party SDK. In Sydney's financial services sector, where banks and fintechs run Java backends under strict audit expectations, a broken logging rule turns into an audit finding rather than a small bug.
An appender is where output ends up; a filter decides whether a message gets that far. Both are ordinary Java objects with ordinary collaborators, so both can be exercised in a fast unit test without starting Spring, reading log files, or scraping standard output from the build. This article covers capturing log events in memory, exercising filter decisions, protecting context data, and keeping the whole thing deterministic on a shared CI node.
The payoff is locality. A capture-and-assert test returns in milliseconds and points at the exact decision that failed, whereas a log-scraping integration test tells you something broke hours later and leaves you squinting at timestamps. For agile product teams — and most Australian teams are, whether based in Melbourne, Brisbane or a regional town — that difference shapes how freely you can refactor logging configuration.
Why logging behaviour is worth testing
A filter is a decision point with real business rules hidden inside it. Deny lists, allow lists, regex patterns, level thresholds: each one encodes a policy that a product owner would recognise. If the policy breaks, no test fails and the leak simply ships, because a broken filter fails quietly by design.
An appender is the destination, and the destination is often where the damage lands. A routing appender that separates audit traffic from application traffic, a JSON layout that downstream tooling parses, a rolling policy that keeps yesterday's file around for support. A malformed layout produces logs nobody can query, which is worse than no logs at all.
So logging deserves the same attention as the rest of the domain logic. It is also cheap to test, since no container, network call or file watcher is involved.
Setting up a test harness
Every harness starts with a test-scoped configuration. Add a logback-test.xml under src/test/resources for Logback, or a log4j2-test.xml for Log4j 2, and keep production configuration files off the test classpath entirely. Both files normally define a single root appender and a level permissive enough to let events through.
Then capture events in memory rather than writing them to disk. Logback's ListAppender is the usual choice:
ListAppender<ILoggingEvent> capture = new ListAppender<>();
capture.start();
Logger logger = (Logger) LoggerFactory.getLogger(AuditRules.class.getName());
logger.detachAndStopAllAppenders();
logger.addAppender(capture);
logger.setLevel(Level.INFO);
Log4j 2 ships an equivalent ListAppender in its core test support, and both frameworks let you narrow the logger under test to a specific name so unrelated messages stay out of your assertions. The same capture-and-isolate pattern applies to other moving parts of a service, and the unit testing tutorials pages walk through comparable harnesses for mocked clients, REST endpoints and asynchronous code.
Testing appenders with in-memory capture
With the capture attached, call the code under test and inspect the recorded events. Assert on structure: the level, the logger name, the marker, the throwable proxy and the MDC map. Asserting on the fully rendered message is tempting and brittle, since timestamps, thread names and machine-specific paths appear in most layouts.
When the appender's job is to transform output — a JSON layout, a pattern encoder, a routing appender that separates audit traffic from everything else — assert on the encoded bytes rather than the event object. Attach an OutputStreamAppender over a ByteArrayOutputStream, run the code, then parse the captured text with Jackson and check the fields you care about.
Asynchronous appenders need patience. Logback's AsyncAppender and Log4j 2's async appender hand events to a background thread, so a direct size check can read zero and fail for entirely the wrong reason. Poll with Awaitility, or wait until the captured list stops growing, and always stop the appender during teardown so a stray worker thread does not outlive the test.
Exercising filter decisions
Filters are the easiest part of logging to test because they are decision functions. In Logback you implement Filter<ILoggingEvent> and return ACCEPT, DENY or NEUTRAL from decide(...); a TurboFilter uses the same three outcomes but receives the marker, logger, level, message and throwable directly. Construct the filter, build a LoggingEvent, invoke the method and assert the outcome.
Log4j 2 takes a similar shape: subclass AbstractFilter and let onMatch and onMismatch pick the result, or test the built-in filters such as ThresholdFilter, RegexFilter and DynamicThresholdFilter. Table-driven JUnit 5 tests suit this style well, with one parameterised case per level or per payload.
TurboFilters deserve extra care. They register on the LoggerContext and affect every logger beneath it, so a filter left behind by one test quietly changes the behaviour of the next. Attach it with loggerContext.addTurboFilter(...) and remove it in an @AfterEach block. The same caution applies to broad shared loggers in a large suite, where a single stray appender can flood hundreds of unrelated assertions.
The strongest assertion is negative. Attach the filter and the capture appender together, log a payload the rule is meant to block — a PAN with digits, an internal hostname — and confirm the capture list stays empty. A positive assertion that the filter returned DENY proves the method's contract; the empty capture proves the rule actually protects the destination.
Preserving context data correctly
Context data is where logging tests most often go wrong. SLF4J's MDC and Log4j 2's ThreadContext carry request identifiers, tenant names and correlation ids, and both are bound to the current thread. In Logback, MDC.put("requestId", id) ends up in the event's MDC property map, so you can assert that the captured event carries the value you expected.
Asynchronous logging complicates the picture. MDC values are copied into the event when the event is created, so they usually survive the handoff to a background thread, but a custom ThreadLocal read inside your own appender will not. If a filter depends on context, set that context before logging and clear it afterwards rather than assuming a worker thread shares your thread locals.
Markers are the other piece of context worth asserting. An org.slf4j.Marker named AUDIT supports routing, and a marker filter can accept only marked messages. Assert that the captured event carries the marker you expect, and use it in a filter test to prove routing decisions.
Finally, resist asserting on timestamps. Sydney clocks jump forward in late October and back in early April as daylight saving starts and ends, so a test expecting an AEST-formatted timestamp fails twice a year. If a timestamp genuinely matters, inject a fixed Clock into the code that produces it.
Comparing the main approaches
Each framework exposes different hooks, so it helps to line them up before writing a harness. The rows below compare the in-memory capture mechanism, the filter extension point, the context API and the trap most likely to cost you an afternoon.
| Framework | In-memory capture | Filter extension point | Context API | Main trap |
|---|---|---|---|---|
| Logback | ListAppender in core.read |
Filter<ILoggingEvent>, TurboFilter |
MDC via SLF4J | Logger levels and appenders are shared globally |
| Log4j 2 | ListAppender and InMemoryAppender in core test support |
AbstractFilter, ThresholdFilter, RegexFilter |
ThreadContext |
Plugin packages must be present on the test classpath |
| Log4j 1.x (legacy) | Custom AppenderSkeleton subclass |
Filter chain attached to a category | MDC, thread-bound | Still found in older enterprise estates; migrate before testing |
| Any framework | OutputStreamAppender over ByteArrayOutputStream |
Not used — inspects encoded output | Not used | Best choice when a layout or JSON encoder is under test |
Choose by project rather than by preference. For a Logback or Log4j 2 codebase the in-memory appender is usually the shortest path to a useful assertion, while the custom stream appender earns its keep when the encoding itself is what you are testing.
Legacy Log4j 1.x still turns up in older Australian enterprise systems and a handful of long-running government tenders, but new tests there are a smell. Migrate to SLF4J with Logback or Log4j 2 first, then write the capture-based tests once. Large Sydney estates run by Atlassian, Canva and REA Group have settled on modern facades precisely because they make this kind of testing possible.
Practical checks before you commit the change
Two short checklists keep a logging test suite honest rather than flaky.
For appenders:
- Attach one in-memory appender, then detach it and restore the original logger level during teardown.
- Assert on level, logger name, marker and context map instead of on rendered message text.
- Parse captured bytes with Jackson when a pattern layout or JSON encoder is under test.
- Await the capture size when the appender is asynchronous, and stop it before the test ends.
For filters:
- Cover the accept, deny and neutral paths with table-driven cases.
- Add and remove TurboFilters on the
LoggerContextso they never leak between tests. - Prove the negative by logging a blocked payload and asserting that nothing reached the appender.
- Clear MDC and ThreadContext so request identifiers never bleed across cases.
None of this needs a running server, which is precisely why it suits a tight feedback loop. A developer in Perth can add a case for a new rule — say, blocking a customer account number before it reaches the audit appender at Woodside-style volume — and see the result immediately, no worries required. Your next step is small and specific: copy the filter class you care about into src/test/java, write one deny case and one accept case against a ListAppender, and run mvn -Dtest=LoggingRuleTest test from the project root before opening the pull request.