Search code examples
javaspringspring-bootlog4j

Log4j prints json key name when value is null


I am having a problem with printing my context variables by log4j. If variable is null then it's printed like: { "status":"${ctx:status}" }

But I want it to be printed like: { "status":"" }

Please share your ideas with me.


Solution

  • I wanted to add some details for s7vr's answer. I totally agree with answer, but there is work around. The issue with printing empty value is depended on jackson-databind library. If you use value pattern as below

    <KeyValuePair key="status" value="$${ctx:status:-}"/>
    

    and want to put empty string in final json object, you can use the version of jackson-databind no newer than 2.10.5.

    This means the following configuration will work:

    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
        <version>2.14.1</version>
    </dependency>
    
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.10.5</version>
    </dependency>