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