Spring Boot JSON Logging with User and Session
How to add user and session data to Spring Boot logs without losing your mind.

Logs are like a black box: when everything's fine, you forget they exist, but when a bug hits production, you're digging through hundreds of lines looking for a needle. Spring Boot defaults to plain text logs—great for humans, but a nightmare for machine parsing.
JSON Logging: A Developer's Lifesaver
Switching to JSON format is like replacing a crumpled sticky note with a structured spreadsheet. The video shows how to configure Logback or Log4j2 to output logs as JSON objects with fields: timestamp, level, message, and—crucially—user and session.
Why bother? Imagine a user on production complains something broke. You check the logs but see a bunch of identical messages from different users. Without context, you're guessing. With userId and sessionId in every log, you filter by user instantly and see their entire action chain. Magic, right?
How to Add User and Session to Logs?
The simplest way is using MDC (Mapped Diagnostic Context)—a pocket in the logging framework where you can stash any data, and it automatically appears in every log from the current thread. In Spring Boot, do this via a filter or interceptor:
- Create a filter that, before processing a request, puts userId and sessionId from SecurityContext or HTTP session into MDC.
- Configure the logger layout to output JSON, specifying to pull those fields from MDC.
- Done—every log now carries context.
Oh, and don't forget to clear MDC after the request, otherwise data leaks into another thread—a fun bug where one user sees another's logs.
METABYTE Studio comment: We've been burned by text logs too before switching to JSON. Now debugging feels like a game of "find the cat"—except you're sure the cat is there, no guessing needed.
NEXT STEP
Liked the approach?
We apply the same principles to client projects: AI, automation, products that don't die after launch.