如何使用Java代码配置Logback来设置日志级别?

时间:2011-11-01 13:27:25

标签: java slf4j logback

除了将org.springframework.data.document.mongodb日志记录级别设置为DEBUG之外,我想使用默认的SLF4J + Logback配置。

如何使用Java代码执行此操作?

我没有使用XML,而且这个决定是在运行时做出的。

2 个答案:

答案 0 :(得分:10)

以下对我有用但通常这不是一个好主意。您的代码将依赖于Logback(您无法选择SLF4J背后的另一个日志框架)。

final org.slf4j.Logger logger = 
    org.slf4j.LoggerFactory.getLogger("test.package");
if (!(logger instanceof ch.qos.logback.classic.Logger)) {
    return;
}
ch.qos.logback.classic.Logger logbackLogger = 
    (ch.qos.logback.classic.Logger) logger;
logbackLogger.setLevel(ch.qos.logback.classic.Level.TRACE);
logger.trace("some log");

答案 1 :(得分:5)

根据logback-classic并不是一个好主意,因为@palacsint说。您可以使用Java的Reflection API实现您想要的功能。请注意,由于使用了反射,这种方法会给您的程序带来一些开销。

用法:

LogbackUtils.setLogLevel("com.stackoverflow.sample", "DEBUG")

代码:

public  static final String LOGBACK_CLASSIC        = "ch.qos.logback.classic";
public  static final String LOGBACK_CLASSIC_LOGGER = "ch.qos.logback.classic.Logger";
public  static final String LOGBACK_CLASSIC_LEVEL  = "ch.qos.logback.classic.Level";
private static final Logger logger                 = LoggerFactory.getLogger(LogbackUtils.class);

/**
 * Dynamically sets the logback log level for the given class to the specified level.
 *
 * @param loggerName Name of the logger to set its log level. If blank, root logger will be used.
 * @param logLevel   One of the supported log levels: TRACE, DEBUG, INFO, WARN, ERROR, FATAL,
 *                   OFF. {@code null} value is considered as 'OFF'.
 */
public static boolean setLogLevel(String loggerName, String logLevel)
{
    String logLevelUpper = (logLevel == null) ? "OFF" : logLevel.toUpperCase();

    try
    {
        Package logbackPackage = Package.getPackage(LOGBACK_CLASSIC);
        if (logbackPackage == null)
        {
            logger.info("Logback is not in the classpath!");
            return false;
        }

        // Use ROOT logger if given logger name is blank.
        if ((loggerName == null) || loggerName.trim().isEmpty())
        {
            loggerName = (String) getFieldValue(LOGBACK_CLASSIC_LOGGER, "ROOT_LOGGER_NAME");
        }

        // Obtain logger by the name
        Logger loggerObtained = LoggerFactory.getLogger(loggerName);
        if (loggerObtained == null)
        {
            // I don't know if this case occurs
            logger.warn("No logger for the name: {}", loggerName);
            return false;
        }

        Object logLevelObj = getFieldValue(LOGBACK_CLASSIC_LEVEL, logLevelUpper);
        if (logLevelObj == null)
        {
            logger.warn("No such log level: {}", logLevelUpper);
            return false;
        }

        Class<?>[] paramTypes =  { logLevelObj.getClass() };
        Object[]   params     =  { logLevelObj };

        Class<?> clz    = Class.forName(LOGBACK_CLASSIC_LOGGER);
        Method   method = clz.getMethod("setLevel", paramTypes);
        method.invoke(loggerObtained, params);

        logger.debug("Log level set to {} for the logger '{}'", logLevelUpper, loggerName);
        return true;
    }
    catch (Exception e)
    {
        logger.warn("Couldn't set log level to {} for the logger '{}'", logLevelUpper, loggerName, e);
        return false;
    }
}

// getFieldValue() method omitted for bravity from here,
// but available at GitHub link below.

包含测试的完整代码:Github Gist