Search code examples
javalog4jlog4j2

Using log4j1.2-2 bridge, is it possible to dynamically configure the log settings


We are using the log4j1 to log4j2 bridge,

log4j-1.2-api-2.17.1.jar

And our code uses the PropertyConfigu

System.getProperty( "appserver.Name" );
System.setProperty( "appserver.Name", "/usr/local/logs/server3" );
l4jprops.put( "appserver.Name", "/usr/local/logs/server3" );    

            
PropertyConfigurator.configure( l4jprops );
logger = Logger.getLogger(PfsSystemPropertiesServlet.class.getName());

Here is an example log4j setting.

log4j.appender.AuthAppender.File=${appserver.Name}/log4j_api_auth.log
log4j.appender.AuthAppender.DatePattern='.'yyyy-MM-dd

This currently doesnt seem to write the logs as we want, how can we get this code to work with the bridge. That class available.


Solution

  • Until Log4j 2.17.1, PropertyConfigurator has been a no-op. That is going to change in the upcoming release (cf. source code): your code should work without any changes.

    In order to test the new release, add the snapshots repository:

    <repositories>
      <repository>
        <id>apache.snapshots</id>
        <name>Apache Snapshot Repository</name>
        <url>https://repository.apache.org/snapshots</url>
        <releases>
          <enabled>false</enabled>
        </releases>
      </repository>
    </repositories>
    

    and set the version of log4j-1.2-api to 2.17.2-SNAPSHOT:

    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-1.2-api</artifactId>
        <version>2.17.2-SNAPSHOT</version>
    </dependency>
    

    Edit: If you can't use snapshots or wait for the next release, the behavior of PropertyConfigurator can be emulated as follows:

    import org.apache.log4j.config.PropertiesConfiguration;
    import org.apache.logging.log4j.LogManager;
    import org.apache.logging.log4j.core.LoggerContext;
    import org.apache.logging.log4j.core.config.Configuration;
    import org.apache.logging.log4j.core.config.ConfigurationSource;
    import org.apache.logging.log4j.core.config.Configurator;
    import org.apache.logging.log4j.core.config.NullConfiguration;
    
    // PropertiesConfiguration only accepts an InputStream in 2.17.1
    final ByteArrayOutputStream os = new ByteArrayOutputStream();
    l4jprops.save(os, null);
    final InputStream is = new ByteArrayInputStream(os.toByteArray());
    // Initialize to prevent automatic configuration.
    Configurator.initialize(new NullConfiguration());
    final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
    final Configuration config = new PropertiesConfiguration(ctx, new ConfigurationSource(is), 0);
    Configurator.reconfigure(config);