简体   繁体   English

Java - 动态更改日志记录级别

[英]Java - dynamically change logging level

I would like to be able to tell the JVM to stop logging certain level of messages at some point in the execution chain. 我希望能够告诉JVM在执行链中的某个点停止记录某些级别的消息。 At some point I want to only log messages with SEVERE level, so I was thinking of doing this: 在某些时候我想只记录具有SEVERE级别的消息,所以我想这样做:

    for(Enumeration<String> loggerNames = logManager.getLoggerNames(); loggerNames.hasMoreElements();){
        String name = loggerNames.nextElement();
        Logger nextLogger = logManager.getLogger(name);
        if(nextLogger != null)
            nextLogger.setLevel(Level.SEVERE);
    }

Is there a cleaner way to achieve the same logic ie set a global variable that would stop printing to log unless SEVERE? 有没有更简洁的方法来实现相同的逻辑,即设置一个全局变量,停止打印到日志除非严重? I need to distinguish between Console output (in test) and file output in live, so I could potentially set these level on the handler (console and File)? 我需要区分控制台输出(在测试中)和实时文件输出,所以我可能会在处理程序(控制台和文件)上设置这些级别?

ANSWERING MY OWN QUESTION: 回答我自己的问题:

This is exactly what I needed: 这正是我所需要的:

Handler[] handlers =
  Logger.getLogger( "" ).getHandlers();
for ( int index = 0; index < handlers.length; index++ ) {
  handlers[index].setLevel( Level.SEVERE);
}

To control you application configuration dynamically, a common way is to use JMX. 要动态控制应用程序配置,常用的方法是使用JMX。

JConsole, part of the jdk, allows you to control MBeans manually but you could also access them programatically. JConsole是jdk的一部分,允许您手动控制MBean,但您也可以以编程方式访问它们。

You can use JMX to control MBeans as described in this page . 您可以使用JMX来控制MBean,如本页所述

With log4j you can change the level of the root logger. 使用log4j,您可以更改根记录器的级别。

This may work: 这可能有效:

logManager.getLogger( "" ).setLevel(Level.SEVERE);

or use Logger.getParent() to find the root logger 或使用Logger.getParent()查找根记录器

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

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