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());