How to Disable Loggers of a Class or of Whole Package

How to disable loggers of a class or of whole package?

In Log4j you can specify a logging level for specified package, class or logger identified by string. You just simply write this in log4j.properties file:

log4j.logger.<your package> = DEBUG|INFO|OFF|WARN...

How to disable log4j logging from Java code

So, you have 3 loggers defined, including the root:

log4j.rootLogger=warn, stdout
log4j.logger.ac.biu.nlp.nlp.engineml=info, logfile
log4j.logger.org.BIU.utils.logging.ExperimentLogger=warn

Unfortunately, to disable them programatically, you need to specify ALL OF THEM in the code:

Logger.getLogger("ac.biu.nlp.nlp.engineml").setLevel(Level.OFF);
Logger.getLogger("org.BIU.utils.logging.ExperimentLogger").setLevel(Level.OFF);
Logger.getRootLogger().setLevel(Level.OFF);

Here's how to reset it back to what's set in the config file.

Disable log output from libraries

An example of turning off logging in log4j 1.x was to add the following xml tag into log4j.xml. The category name is the package path to the root of the library you want to ignore logging from. For example to ignore log4j logging from the apache tiles library you would use the following:

<category name="org.apache.tiles">
<priority value = "off" />
</category>

Is there a way to disable java.util.logging and enable it back later?

For a global impact you can use LogManager.reset() as your call to disable logging and to re-enable logging you can LogManager.readConfiguration(). However, there are some major flaws in what actually gets reloaded. The newer JDK9 method LogManager.updateConfiguration should be used instead.

If you know the logger name you can edit your logging.properties to modify the level of that offending logger or create a filter.

From code you can locate the logger and change it's level to OFF or something higher than the log messages you are seeing.

final Logger chatty = Logger.getLogger("somelogger");
final Level oldLevel = chatty.getLevel();
chatty.setLevel(Level.OFF);
try {
taskThatMakesUnnecessaryLogs();
} finally {
chatty.setLevel(oldLevel);
}


Related Topics



Leave a reply



Submit