1

Is it possible to reference MDC Variables in the log-message instead of the pattern using slf4j with log4j-impl?

I have the following piece of code:

package example;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.slf4j.MDC.MDCCloseable;

public class Stackoverflow {

    private static final Logger log = LoggerFactory.getLogger(Stackoverflow.class);

    public static void main(String[] args) {
        try (MDCCloseable _unused = MDC.putCloseable("url", "https://google.com/")) {
            log.info("blabla some log message url=%mdc{url}");
        }
    }
}

But the placeholder %mdc{url} will not be replaced. I also tried using %X{url} and %MDC{url} (see https://logging.apache.org/log4j/2.x/manual/layouts.html ).

When changing the ConversionPattern to include either of these placeholders the value is replaced. But I would like to reference the variable in the message and not in the pattern.

My full log4j config looks like this:

# Root logger option
log4j.rootLogger=INFO, stdout

# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

I'm using slf4j version 1.7

Felix
  • 2,256
  • 2
  • 15
  • 35
  • Why do you need to do that? The MDC will all be printed in the log output right next to the message. – Thilo Nov 13 '19 at 12:46
  • @Thilo I would like not to include the MDC in the Pattern because the Pattern will be specified by an underlying system which I don't have any access to in the near future – Felix Nov 13 '19 at 12:49
  • 1
    That is an odd arrangement. Whoever is deploying the application should be able to configure the logging properly. – Thilo Nov 13 '19 at 12:51

1 Answers1

2

It seems a bit odd that you want to do this, as the MDC will all be printed automatically by the logging system right next to your message (making it redundant to print it again), but you can get to the value using MDC.get:

log.info("blabla some log message url={}", MDC.get("url"));
Thilo
  • 257,207
  • 101
  • 511
  • 656