Search code examples
logbackmdc

Logback MDC print variables at runtime


I was wondering if it is possible to print a previously added MDC value from a logger call?

example:

MDC.put("user","tom")

log.info("Hello %X{user}");

instead of adding it to the layout pattern.

The reason for this is that I call MDC elsewhere and I log at the end of my logic, but I want to conditionally log different values. I know a workaround might be different appenders.


Solution

  • Since MDC is essentially a map, you can always use .get() to retrieve values previously stored in it:

    MDC.put("user", "tom");
    
    log.info("Hello, {}", MDC.get("user"));