0
votes

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 (e.g. %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 {}

2

2 Answers

1
votes

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.

0
votes

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>