0
votes

You can see in https://logging.apache.org/log4j/2.x/manual/customloglevels.html the numerical values corresponding to built-in log4j2 logging levels, for example INFO->400. How can you refer to it in patternlayout resp. in JDBC Logger configuration?

I have an old log4j 1.x config for JDBC where it was referred as %iprio.

A workaround is to use

level{OFF=0,FATAL=100,ERROR=200,WARN=300,INFO=400,DEBUG=500,TRACE=600,ALL=1000}

but I am not very happy about that.

1

1 Answers

1
votes

It sounds like you want to log the integer value of the log level instead of the name and you don't want to use the labeling feature of the PatternLayout's level parameter.

One possible solution would be to create a custom Lookup, here is some sample code:

package example;

import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import org.apache.logging.log4j.core.lookup.StrLookup;

@Plugin(name = "level", category = "Lookup")
public class LevelLookup implements StrLookup{
    /**
     * Lookup the value for the key.
     * @param key  the key to be looked up, may be null
     * @return The value for the key.
     */
    public String lookup(String key) {
        return null;
    }


    /**
     * Lookup the value for the key using the data in the LogEvent.
     * @param event The current LogEvent.
     * @param key  the key to be looked up, may be null
     * @return The value associated with the key.
     */
    public String lookup(LogEvent event, String key) {
        return String.valueOf(event.getLevel().intLevel());
    }
}

Next, here is a sample configuration using the new lookup - note the ${level:}:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] ${level:} %logger{36} - %msg%n" />
        </Console>
    </Appenders>

    <Loggers>
        <Root level="debug">
            <AppenderRef ref="Console" />           
        </Root>
    </Loggers>
</Configuration>

Here is some sample code that performs some logging:

package example;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class SomeClass {

    private static final Logger log = LogManager.getLogger();   

    public static void main(String[] args){
        log.debug("This is some debug!");
        log.info("Here's some info!");
        log.error("Some erorr happened!");
    }
}

and finally here is the output:

22:49:29.438 [main] 500 example.SomeClass - This is some debug!
22:49:29.440 [main] 400 example.SomeClass - Here's some info!
22:49:29.440 [main] 200 example.SomeClass - Some erorr happened!

Hope this helps!