All,
I'm coming from a log4j v1.x background where this was easy to do:
String loggerName = "com.example.Class";
Logger log = LogManager.exists(loggerName);
if(null != log) {
log.setLevel(targetLevel);
}
This appears no longer to be possible -- or at least easy -- and I've
seen at least two techniques on StackOverflow which result in the same
behavior: the log-level threshold for *every logger everywhere* gets set
to the target level.
For example, setting the log-level for the logger called "foo" to TRACE
ends up filling my log with stuff from completely unrelated
loggers/classes/etc.
Here is one technique[1]
String loggerName = "com.example.Class";
LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
Configuration config = ctx.getConfiguration();
LoggerConfig loggerConfig = config.getLoggerConfig(loggerName);
loggerConfig.setLevel(level);
ctx.updateLoggers(); // This causes all Loggers to refetch information
from their LoggerConfig.
I tried both with and without the ctx.updateLoggers() call.
Here is another technique[2]:
Configurator.setLevel(loggerName, level);
This reconfigures everything just like the one above.
The final technique (still in the same SO question) is this:
final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
final Configuration config = ctx.getConfiguration();
LoggerConfig loggerConfig = config.getLoggerConfig(logger.getName());
LoggerConfig specificConfig = loggerConfig;
// We need a specific configuration for this logger,
// otherwise we would change the level of all other loggers
// having the original configuration as parent as well
if (!loggerConfig.getName().equals(logger.getName())) {
specificConfig = new LoggerConfig(logger.getName(), level, true);
specificConfig.setParent(loggerConfig);
config.addLogger(logger.getName(), specificConfig);
}
specificConfig.setLevel(level);
ctx.updateLoggers();
This does not seem to set the log level for all loggers to e.g. TRACE
but it also doesn't seem to set the actual logger. (I can see e.g. DEBUG
and TRACE logs from other loggers, so it's not an issue with the appender).
What is the recommended technique for changing a single logger's
threshold in log4j2? I realize that the best thing to do would be to
"just configure it correctly the first time" but in reality, you
sometimes just have to enable TRACE logging in production to figure out
what the hell is happening.
Thanks,
-chris
[1] Adapted from https://stackoverflow.com/a/23434603/276232
[2] Adapted from https://stackoverflow.com/a/44678752/276232
---------------------------------------------------------------------
To unsubscribe, e-mail: log4j-user-unsubscr...@logging.apache.org
For additional commands, e-mail: log4j-user-h...@logging.apache.org