简体   繁体   English

如何将记录器包裹在 slf4j 中?

[英]How to get the logger wrapped in slf4j?

Is it possible to get the logger wrapped by slf4j ?是否有可能让 slf4j 包装记录器?

For example, in debug mode, when I inspect org.slf4j.LoggerFactory.getLogger(loggerName) , I can see the logger (here, java.util.logging ) :例如,在调试模式下,当我检查org.slf4j.LoggerFactory.getLogger(loggerName) ,我可以看到记录器(这里是java.util.logging ):

java.util.logging 记录器

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)); 

I've found a solution using reflection.我找到了使用反射的解决方案。 Looking for the "logger" field in the slf4j Logger.在 slf4j 记录器中寻找“记录器”字段。

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 ?但也许使用 slf4j API 存在更好的解决方案?

In order to find which implementation is used by slf4j(eg logback/log4j like in spring-boot) you could use the below way to extract that information为了找到 slf4j 使用的实现(例如,spring-boot 中的 logback/log4j),您可以使用以下方法来提取该信息

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

Output输出

ch.qos.logback.classic.LoggerContext[default]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM