Skip to content
Advertisement

How to log output of just a specified framework class in Log4J

I need to log the output of a specific Spring class (org.springframework.core.log.LogFormatUtils) to a given appender (Graylog in the end, but I used a FileAppender for testing purposes – doesn’t matter here). I’m aware that generally, this could be done quite simple by using

<Loggers>
        <Logger name="org.springframework.core.log.LogFormatUtils" level="DEBUG">
            <AppenderRef ref="FileAppender"/>
        </Logger>
        <Root level="debug" includeLocation="true">
            <AppenderRef ref="ConsoleAppender"/>
        </Root>
</Loggers>

However, this does not work – it outputs nothing. If I change the logger’s name / package reference to “org.springframework” it works as expcted, but I’m not interested in the bunch of inforamtion coming along that way. Additionally, if I denote something like com.myapp.mypackage, it also works. So, are there some caveats or steps to perform before I can log Spring framework output in general?

Advertisement

Answer

public static void traceDebug(Log logger, Function<Boolean, String> messageFactory) {
    if (logger.isDebugEnabled()) {
        boolean traceEnabled = logger.isTraceEnabled();
        String logMessage = messageFactory.apply(traceEnabled);
        if (traceEnabled) {
            logger.trace(logMessage);
        }
        else {
            logger.debug(logMessage);
        }
    }
}

The method is the only method in the LogFormatUtils class that uses the Log object, but the Log object it uses is passed from other classes, that is to say, logger name of the Log object is not org.springframework.core.log.LogFormatUtils, you can change logger’s name to org.springframework and add %logger to PatternLayout to find the real logger’s name you need.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement