I have the following console appender;
<Console name="STDOUT">
<PatternLayout pattern="%highlight{%d [%t] %notEmpty{[%marker] }%-5level: %msg %X%n%throwable}"/>
<ThresholdFilter level="trace"/>
</Console>
The problem is that the pattern I have used here outputs an empty ThreadContext ( {}
). I do not want to use specific key names (eg %X{username}
) because the system is quite extensive and the set of keys varies. Example output:
2017-09-26 10:39:55,396 [main] INFO : Starting the internal HTTP client {}
A bit shorter that using a ScriptPatternSelector would be asking log4j to replace "{}" with an empty string for the MDC. To do so, replace "%X" with "%equals{%X}{{}}{}" in your log4j.xml or log4j2.xml.
Okay, I solved my problem by making use of the ScriptPatternSelector
. The script below checks if the logEvent's MDC is not empty and changes the pattern if true;
<Console name="STDOUT">
<PatternLayout>
<ScriptPatternSelector defaultPattern="%highlight{%d [%t] %notEmpty{[%marker] }%-5level: %msg%n%throwable}">
<Script name="MDCSelector" language="javascript"><![CDATA[
result = null;
if (!logEvent.getContextData().size() == 0) {
result = "WithMDC";
} else {
result = null;
}
result;
]]>
</Script>
<PatternMatch key="WithMDC" pattern="%highlight{%d [%t] %notEmpty{[%marker] }%-5level: %msg %X%n%throwable}"/>
</ScriptPatternSelector>
</PatternLayout>
<ThresholdFilter level="trace"/>
</Console>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.