GitHub user paladox edited a comment on the discussion: Help with migrating
from log4j to log4j2 (we also use a slf4j -> log4j)
I've done the following:
```
if (name == null) {
Configurator.setAllLevels("", newLevel);
} else {
LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
ctx.getLoggerRegistry()
.getLoggers()
.forEach(
logger -> {
String loggerName = logger.getName();
if (loggerName.contains(name)) {
Configurator.setLevel(loggerName, newLevel);
}
});
}
```
Per your recommendation to use the Configurator class. Does that look good to
you?
This should work with log4j 1.x & slf4j alongside log4j2 (fetching all the
loggers).
For resetting, I have:
```
private static void reset() {
LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
org.apache.logging.log4j.core.config.Configuration config =
ctx.getConfiguration();
ctx.getLoggerRegistry()
.getLoggers()
.forEach(
logger -> {
Level original = ORIGINAL_LEVELS.get(logger.getName());
if (original != null) {
Configurator.setLevel(logger.getName(), original);
}
});
if (ORIGINAL_ROOT_LEVEL != null) {
config.getRootLogger().setLevel(ORIGINAL_ROOT_LEVEL);
}
ctx.updateLoggers();
}
```
We don't set a configuration file (we allow someone to set one, but don't
actively use it as a default). Do you know how I can convert:
```
private static void reset() throws MalformedURLException {
for (Logger logger : getCurrentLoggers()) {
logger.setLevel(null);
}
String path = System.getProperty(JAVA_OPTIONS_LOG_CONFIG);
if (Strings.isNullOrEmpty(path)) {
PropertyConfigurator.configure(Loader.getResource(LOG_CONFIGURATION));
} else {
PropertyConfigurator.configure(URI.create(path).toURL());
}
}
@SuppressWarnings({"unchecked", "JdkObsolete"})
private static ImmutableList<Logger> getCurrentLoggers() {
return
ImmutableList.copyOf(Iterators.forEnumeration(LogManager.getCurrentLoggers()));
}
```
to log4j2? I did my best to, but it seems setting log levels to null, only
makes for example a logger that had WARN as its default, go to INFO. Unlike in
log4j1 when it worked. I found a workaround in creating a original logger map,
but preferably if there's a way to match log4j, I'd prefer that.
https://gist.github.com/paladox/ee30542a176c3d95fe337264974090c0 is the full
code for the new updated code and
https://github.com/GerritCodeReview/gerrit/blob/master/java/com/google/gerrit/sshd/commands/SetLoggingLevelCommand.java
for the original.
GitHub link:
https://github.com/apache/logging-log4j2/discussions/3914#discussioncomment-14310844
----
This is an automatically sent email for [email protected].
To unsubscribe, please send an email to: [email protected]