Monday, July 30, 2012

How to change logging level in runtime

Changing the log logging level in runtime is important  mainly in production environment where you might want to have debug logging for limited amount of time.

Well, changing the root logger is very simple - assuming you have an input parameter with the wanted logging level simply get the root logger and set by the input logging level, such as:

Logger root = Logger.getRootLogger();

//setting the logging level according to input
if ("FATAL".equalsIgnoreCase(logLevel)) {
    root.setLevel(Level.FATAL);
}else if ("ERROR".equalsIgnoreCase(logLevel)) {
    root.setLevel(Level.ERROR);
}

However - the common case is that we maintain log instance per class, for example:

class SomeClass{

//class level logger
static Logger logger - Logger.getLogger(SomeClass.class);
}

and setting the root logger is not enough, since the class level logger will not be affected.

The trick is to remember get all the loggers in the system and change their logging level too.
For example:

Logger root = Logger.getRootLogger();
Enumeration allLoggers = root.getLoggerRepository().getCurrentCategories();

//set logging level of root and all logging instances in the system
if ("FATAL".equalsIgnoreCase(logLevel)) {
    root.setLevel(Level.FATAL);
    while (allLoggers.hasMoreElements()){
        Category tmpLogger = (Category) allLoggers.nextElement();
        tmpLogger .setLevel(Level.FATAL);
    }
}else if ("ERROR".equalsIgnoreCase(logLevel)) {
    root.setLevel(Level.ERROR);
    while (allLoggers.hasMoreElements()){
        Category tmpLogger = (Category) allLoggers.nextElement();
        tmpLogger .setLevel(Level.ERROR);
    }
}


So just wrap it up in a service class and call it from your controller, with a dynamic logLevel String parameter which represent the logging level you wish to set your system to.

If any of you need the complete solution, please let me know.

Reference to the basic approach is in this link.

1 comment:

  1. Hey Gal,

    I really think you've got an awesome blog here, especially the Java content. Not to mention the awesome Katana! I'm a community blog curator for DZone. I wanted to talk with you about potentially featuring your blog on DZone's content portals. Send me an email at mpron [at] dzone{dot} com and I'll explain the details.

    ReplyDelete