i have an issue, i want to change the logging level of log4j at runtime, i have tried many things with log4j.properties file, i have also tried to written a code which after particular time again reads the properties file and again configure the logger.
but the problem is, i want to change the logging level to DEBUG for one API call, and then when that call is completed, the logger should again change to the previous value..
please help..
If you are using Spring Boot (1.5+), you can use logger endpoint to POST desired logging level.
Calling the
Logger.setLevel
method with the desiredLevel
can alter aLogger
's output level at runtime.The following is an example which demonstrates its usage:
The above outputs:
The above demonstrates how to change the level of one
Logger
namedmyLogger
, but if the levels of all the loggers in the current repository should be changed, then thesetLevel
method on the root logger obtained byLogger.getRootLogger
should be called to change the levels on all the child loggers.The log level of a logger can be changed by calling
setLevel
as described by @coobird. However, there is a catch!When you call
getLogger(name)
, the logging library will return you an existingLogger
object if possible. If two or more threads request a logger with the same name, they will get the same object. If one of the threads callssetLevel
, this will change the logger level for all of the others. That can lead to unexpected behavior.If you really need to do this kind of thing, a better approach would be to create a logger with a different name for the case where you want to logging at a different level.
However, I'm not convinced of the wisdom of the application calling
setLevel
at all. ThesetLevel
method is about filtering the log messages, and you should not be wresting control of logging filtering away from the user / deployer.I think it makes sense to call
setLevel
if a server has a "Controller" thread. That way, you can dynamically change logging level at runtime to debug an issue, and change it back when you are done.But I don't know what happens when it is called from a separate thread.
setLevel method is there only for java.util.logging.Logger and not for org.apache.logging.log4j.Logger
This is how we set log level in apache log4j