如何允许用户对日志级别进行永久性更改?

时间:2016-11-03 17:37:23

标签: java logging spring-boot log4j2

我有一个使用log4j2进行日志记录的Spring Boot应用程序。我需要在运行时调整日志记录级别,并且我已经使用一个简单的RESTful接口来完成该操作,该接口接受记录器名称以及需要设置的级别。我还需要能够对日志记录级别进行永久性更改(仅在某些记录器上)。

a)有没有办法将我的更改保留回log4j配置文件,以便下次启动应用程序时,日志级别是在上一次运行时保留的位置?

b)有没有办法读取配置文件中列出的记录器列表?

谢谢

1 个答案:

答案 0 :(得分:1)

a)如果你有一个配置文件,每次服务器启动它都会用来配置log4j2。您可以创建一个新的配置文件(在容器外部)并在服务器启动时使用它来配置log4j2:

    File file = new File("/config/new/log4j2.xml");             
    final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);     
    ctx.setConfigLocation(file.toURI());

或者只是存储新信息并以编程方式修改log4j

b)试试这个:

public Collection<Logger> getLoggers()

https://logging.apache.org/log4j/2.0/log4j-core/apidocs/org/apache/logging/log4j/core/LoggerContext.html#getLoggers()

这是一个代码示例(在应用程序启动时执行):

    File file = new File(log4jConfigFilePath);      
    final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    ctx.setConfigLocation(file.toURI());

    Collection<org.apache.logging.log4j.core.Logger> collection = ctx.getLoggers();     
    System.out.println(collection.size()); // returns 0 (No loggers instantiated)

    Logger logger = LoggerFactory.getLogger("myLogger");

    collection = ctx.getLoggers();      
    System.out.println(collection.size()); // returns 1 (myLogger instantiated)