Search code examples
log4j2

How to avoid printing of "contextMap" in log4j2 when certain log attributes are based on data added to threadcontext


I want to log 2 custom fields in log4j2 Json Format, out of which one is having fixed value, and other one is derived from ThreadContext. I'm using JsonTemplateLayout to print the log attributes. Here, the attribute deriving its value from ThreadContext is getting printed twice. Once at root level in logging JSON output, and one under "contextMap" key. This "contextMap" key is getting added by log4j2 by default.

<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
   <Appenders>
      <Console name="console" target="SYSTEM_OUT">
          <JsonTemplateLayout eventTemplateUri="classpath:JsonLayout.json">
              <EventTemplateAdditionalField key="myApp" value="MYAPPLICATION" />
             
              <EventTemplateAdditionalField key="customKey1"
                              format="JSON"
                              value='{"$resolver": "mdc", "key": "customKey1"}'/>  
                        
          </JsonTemplateLayout>
      </Console>
   </Appenders>
    <Loggers>
        <Root level="info" additivity="false">
            <AppenderRef ref="console" />
        </Root>
    </Loggers>
</Configuration>

My output is coming as below:

{
    "instant": {
        "epochSecond": 1712749405,
        "nanoOfSecond": 600717045
    },
    "thread": "t1",
    "level": "ERROR",
    "loggerName": "com.example.myapp.Log",
    "message": "custom log msg",
    "contextMap": {
        "customKey1": "customValue"
    },
    "myApp": "MYAPPLICATION",
    "customKey1": "customValue"
}

How to suppress the printing of "contextMap" attribute in log4j2 ?

Version Info:

"org.springframework.boot:spring-boot-starter-log4j2:2.7.18" "org.apache.logging.log4j:log4j-layout-template-json:2.21.1"


Solution

  • You can

    1. either provide your own custom event template layout (copy JsonLayout.json to MyLayout.json in your classpath, edit it to your liking, and point to that in the eventTemplateUri attribute)
    2. or override the contextMap entry to null: <EventTemplateAdditionalField key="contextMap" format="JSON" value='null'/>

    Note: I strongly advise you to not use the JsonLayout.json template. It is there for providing a migration path from the deprecated JSON Layout. Either use EcsLayout.json (the default) or create your own custom one using stringified exception resolvers.