简体   繁体   English

动态更改日志记录级别

[英]Changing level of logging dynamically

I want to change the level of logging for all (about) of my web application controller classes dynamically. 我想动态更改所有(大约)Web应用程序控制器类的日志记录级别。 Each class that does logging contains this code: 每个记录日志的类都包含以下代码:

private static final Logger logger = LoggerFactory
            .getLogger(HomeController.class);

I learned that slf4j doesn't offer the functionality of setting a log level, so that one has to use the underlying log4j: 我了解到slf4j不提供设置日志级别的功能,因此必须使用底层的log4j:

public static void setLogLevel(String level) {
    org.apache.log4j.Logger logger4j = org.apache.log4j.Logger.getRootLogger();
    logger4j.setLevel(org.apache.log4j.Level.toLevel(level.toUpperCase()));

    logger.info("Sample Info After setLevel");
    logger.debug("Sample Debug After setLevel");
    logger.error("Sample Error After setLevel");
    logger.trace("Sample Trace After setLevel");
    logger.warn("Sample Warn After setLevel");
}

My idea is to have a controller method which changes the logLevel and maybe stores it in the database. 我的想法是拥有一个控制器方法来更改logLevel并将其存储在数据库中。 My question is: How I can solve this elegantly without copy and pasting everything in 40+ files and modifying every controller method? 我的问题是:如何才能优雅地解决此问题,而无需将所有内容复制并粘贴到40多个文件中并修改每个控制器方法? Also note that the logger code is static, while my database access is not static. 还要注意,记录器代码是静态的,而我的数据库访问不是静态的。

How I can solve this elegantly without copy and pasting everything in 40+ files and modifying every controller method? 我如何才能优雅地解决此问题,而无需将所有内容复制并粘贴到40多个文件中并修改每个控制器方法?

You use a single controller method, taking the logger name and desired log level as a query parameters, and call the string version of LogManager.getLogger(String name) . 您使用单一控制器方法,将记录器名称和所需的日志级别作为查询参数,然后调用LogManager.getLogger(String name)的字符串版本。

Also saving to the database and re-loading on restart is of course extra work to be done by you. 当然,保存到数据库并在重新启动时重新加载当然是您需要做的额外工作。

Alternatively, the controller can update the Log4j configuration file used at startup, and force Log4j to reload it whenever it's changed, eg by calling PropertyConfigurator.configure(String configFilename) . 或者,控制器可以更新启动时使用的Log4j配置文件,并在更改Log4j时强制重新加载它,例如,通过调用PropertyConfigurator.configure(String configFilename)

You can use Slf4j and externalize your application.properties file . 您可以使用Slf4j并外部化application.properties文件。 You can configure the logging level in this file as per your needs. 您可以根据需要在此文件中配置日志记录级别。

logging.level.com.test=DEBUG
logging.level.org=INFO

I am not sure why you need to store this logging level in the Database. 我不确定为什么您需要将此日志记录级别存储在数据库中。

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

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