How to get the logger wrapped in slf4j?
Asked Answered
P

2

10

Is it possible to get the logger wrapped by slf4j ?

For example, in debug mode, when I inspect org.slf4j.LoggerFactory.getLogger(loggerName), I can see the logger (here, java.util.logging) :

java.util.logging Logger

I want to do something like :

// Get the real logger, cast in java.util.logging
java.util.logging.Logger myLogger = LoggerFactory.getLogger(loggerName))...;
// Use the java.util.logging methods
myLogger.setLevel(Level.parse(level)); 
Pontefract answered 24/1, 2014 at 10:14 Comment(0)
P
10

I've found a solution using reflection. Looking for the "logger" field in the slf4j Logger.

private <T> T getLogger(final String loggerName, final Class<T> loggerClass) {
    final org.slf4j.Logger logger = LoggerFactory.getLogger(loggerName);
    try {
        final Class<? extends org.slf4j.Logger> loggerIntrospected = logger.getClass();
        final Field fields[] = loggerIntrospected.getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            final String fieldName = fields[i].getName();
            if (fieldName.equals("logger")) {
                fields[i].setAccessible(true);
                return loggerClass.cast(fields[i].get(logger));
            }
        }
    } catch (final Exception e) {
        logger.error(e.getMessage());
    }
    return null;
}

Calling with:

java.util.logging.Logger myLogger = getLogger(loggerName, java.util.logging.Logger.class)
// or
org.apache.log4j.Logger myLogger = getLogger(loggerName, org.apache.log4j.Logger.class)

But maybe exists a better solution using the slf4j API ?

Pontefract answered 24/1, 2014 at 15:34 Comment(1)
Thanks for the solution! I had to remove the quotes of "logger" in the return line, so "get" should take the logger instance instead of a string.Noisette
D
1

In order to find which implementation is used by slf4j(e.g. logback/log4j like in spring-boot) you could use the below way to extract that information

System.out.println(StaticLoggerBinder.getSingleton().getLoggerFactory());

Output

ch.qos.logback.classic.LoggerContext[default]
Donothingism answered 15/6, 2021 at 10:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.