I have an application for which I want to have the logging level set to INFO
unless Debug Mode is set in which case I want to set the level to FINEST
.
If I set the level in the properties file it does not get overridden from the program using logger.setLevel(Level.FINEST)
also, if I do not set anything for the .level
field in the properties file, by default the INFO level is taken and again I cannot override to use FINEST
if isDebugEnable().
How can I make this level configurable based on the condition ?
try(InputStream configFile = getClass().getClassLoader().getResourceAsStream("logging.properties")) {
LogManager.getLogManager().readConfiguration(configFile);
} catch (IOException e) {
throw new IllegalStateException("Unable to load default logging properties.", e);
}
if (isDebugEnabled()) {
logger.setLevel(Level.FINEST);
} else {
logger.setLevel(Level.INFO);
}
My config file is as follows:
handlers= java.util.logging.ConsoleHandler
.level= INFO
# default file output is in user's home directory.
java.util.logging.FileHandler.pattern = %h/java%u.log
java.util.logging.FileHandler.limit = 50000
java.util.logging.FileHandler.count = 1
java.util.logging.FileHandler.formatter = java.util.logging.XMLFormatter
# Enable console to set level to FINEST and above.
java.util.logging.ConsoleHandler.level = FINEST
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter
I can do this using as follow, but would like to know if there is a better way to do this. (May be using properties file)
ConsoleHandler consoleHandler = new ConsoleHandler();
setLogLevel();
consoleHandler.setLevel(Level.FINEST);
logger.addHandler(new ConsoleHandler());
If you are setting a
DEBUG
option before startup of the JVM then just package a 2ndlogging.properties
file calleddebug.properties
and change thejava.util.logging.config.file
to point to thedebug.properties
when you want debug options.If you have to set the levels at runtime you'll run in to problems with readConfiguration not resetting all everything after boot of the JVM. Under JDK 8 or older all you can do is call
readConfiguration
to populate the defaults and add more code to fix the broken behavior. Since you just need to set the level on handlers then just add that code.JDK 9 provides an
updateConfiguration
method that will work around the broken behavior of thereadConfiguration
method.