What you're looking for is a log4j2 lookup. It sounds like you're interested specifically in the Context Map Lookup as you mentioned MDC (which is now called ThreadContext
in log4j2 by the way).
Here is a simple example:
package example;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.ThreadContext;
public class ThreadContextExample {
private static final Logger log = LogManager.getLogger();
public static void main(String[] args) {
ThreadContext.put("myKey", "myValue");
log.info("Here's a message!");
}
}
Here is the log4j2.xml configuration:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<JsonLayout compact="false" eventEol="false" stacktraceAsString="true">
<KeyValuePair key="myJsonKey" value="${ctx:myKey}"/>
</JsonLayout>
</Console>
</Appenders>
<Loggers>
<Root level="debug">
<AppenderRef ref="Console"/>
</Root>
</Loggers>
</Configuration>
and finally some sample output (shortened for readability):
{
"thread" : "main",
"level" : "INFO",
"loggerName" : "example.ThreadContextExample",
"message" : "Here's a message!",
...
"myJsonKey" : "myValue"
}