GitHub user ppkarwasz added a comment to the discussion: Help with migrating
from log4j to log4j2 (we also use a slf4j -> log4j)
> 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?
Log4j 1.x didn’t have a separate `Configuration` object, loading a config file
just mutated the global state in place. That’s why your old code needed to
“reset” loggers by setting their levels back to `null` before reapplying the
configuration.
In Log4j 2, `Configuration` is a **standalone object**. To “reset,” you don’t
need to touch individual loggers; you simply build a fresh configuration and
replace the old one:
```java
LoggerContext context = (LoggerContext) LogManager.getContext(false);
String path = System.getProperty(JAVA_OPTIONS_LOG_CONFIG);
URI configLocation = Strings.isNullOrEmpty(path)
? Loader.getResource(LOG_CONFIGURATION).toURI()
: URI.create(path);
// Build a new configuration
Configuration newConfig =
ConfigurationFactory.getInstance().getConfiguration(context, null,
configLocation);
// Replace the old configuration
context.reconfigure(newConfig);
```
This reinitializes the logging system with the new configuration. All logger
levels and appenders are reset to what the new config specifies, no manual
`logger.setLevel(null)` loop is needed anymore.
> [!NOTE]
> The `Configuration` object in Log4j 2 is still mutable, which is why
> utilities like `Configurator.setLevel` work. However, we don’t recommend
> making broader changes to the live configuration: if done in the wrong order,
> you may encounter race conditions or even lose log events. For more advanced
> use cases, prefer building a new configuration as described in [programmatic
> configuration](https://logging.apache.org/log4j/2.x/manual/customconfig.html).
GitHub link:
https://github.com/apache/logging-log4j2/discussions/3914#discussioncomment-14311028
----
This is an automatically sent email for [email protected].
To unsubscribe, please send an email to: [email protected]