Search code examples
javaloggingconfigurationlog4jlog4j2

Set custom name for Log4j2 log level in XML configuration file


I'd like to force my log4j2 to display log level like "Warning" instead of "WARN" etc.

Is it possible to do so? It can't be done programmatically, it must be done in XML configuration file because I'm using it in an already built image so I don't have access to the source code.

I tried something like this but it did nothing.

<CustomLevels>
    <CustomLevel name="Warning" intLevel="300" />
    <CustomLevel name="Information" intLevel="400" />
</CustomLevels>

I'd like to replace default log levels with my custom names.

Edit:

I need something like this, but for JsonTemplateLayout:

<PatternLayout>
   <Pattern>"%level{WARN=Warning, DEBUG=Debug, ERROR=Error, TRACE=Trace, INFO=Info}"</Pattern>
</PatternLayout>

It must be in JSON format using JsonTemplateLayout (no PatternLayout)


Solution

  • I found the solution! :)

    <JsonTemplateLayout eventTemplateUri="classpath:EcsLayout.json">
                 <EventTemplateAdditionalField
                    key="@l"
                    format="JSON"
                    value='{"$resolver": "pattern", "pattern": "%level{WARN=Warning, DEBUG=Debug, ERROR=Error, TRACE=Trace, INFO=Information}"}'/>
    </JsonTemplateLayout>
    

    It's not very elegant, but it works :)

    Edit:

    I'm not sure why, but for ERROR level it didn't work correctly. It changed ERROR to Error, but my @l contained also exception message. I needed to add %ex{none} to my pattern like this:

    {"$resolver": "pattern", "pattern": "%level{FATAL=Fatal, ERROR=Error}%ex{none}"}