Thomas S.
Thomas S.

Reputation: 6335

Log4J 1.2 PropertyConfigurator -> Log4J2

Currently, our application uses Log4J 1.2 and configures it using either

File file = ...
PropertyConfigurator.configure(file.getAbsolutePath());

or

URL url = ...
PropertyConfigurator.configure(url);

I know that the property file format has changed from 1.2 to 2, but what would be a similar way to configure Log4J 2 using a property file at an arbitrary file or URL?

Upvotes: 10

Views: 15868

Answers (2)

Agustí Sánchez
Agustí Sánchez

Reputation: 11223

You can use PropertiesConfigurationBuilder as follows:

// Custom-loaded properties.
Properties props = ... 
// Beware it should be org.apache.logging.log4j.core.LoggerContext class,
// not the one ins spi package!
// Not sure about the meaning of "false".
LoggerContext context = (LoggerContext)LogManager.getContext(false);
Configuration config = new PropertiesConfigurationBuilder()
            .setConfigurationSource(ConfigurationSource.NULL_SOURCE)
            .setRootProperties(props)
            .setLoggerContext(context)
            .build();
 context.setConfiguration(config);
 Configurator.initialize(config);

It's true that using the core classes looks like a hack but the author himself uses them in his tutotrial: https://logging.apache.org/log4j/log4j-2.3/manual/customconfig.html .

Upvotes: 7

Olivier Grégoire
Olivier Grégoire

Reputation: 35427

From Log4J 2's documentation:

// import org.apache.logging.log4j.core.LoggerContext;

LoggerContext context = (org.apache.logging.log4j.core.LoggerContext) LogManager.getContext(false);
File file = new File("path/to/a/different/log4j2.xml");

// this will force a reconfiguration
context.setConfigLocation(file.toURI());

Make sure to refer to org.apache.logging.log4j.core.LoggerContext (defined in the log4j-core artifact, not the log4j-api one) and not to org.apache.logging.log4j.spi.LoggerContext.

Upvotes: 4

Related Questions