9

I would like to be able to tell the JVM to stop logging certain level of messages at some point in the execution chain. At some point I want to only log messages with SEVERE level, so I was thinking of doing this:

    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 i.e. 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)?

2

3 Answers 3

8

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

That worked for me too. The advantage of this pure java approach is that I can do it in groovy too, when libraries have too much logging at the default level (I'm looking at you Apache SSHD).
2

To control you application configuration dynamically, a common way is to use JMX.

JConsole, part of the jdk, allows you to control MBeans manually but you could also access them programatically.

You can use JMX to control MBeans as described in this page.

Comments

0

With log4j you can change the level of the root logger.

This may work:

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

or use Logger.getParent() to find the root logger

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.