使用log4j1.2-2 bridge,是否可以动态配置日志设置

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

我们正在使用 log4j1 到 log4j2 桥,

log4j-1.2-api-2.17.1.jar

而我们的代码使用了 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());

这是一个 log4j 设置示例。

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

这目前似乎没有按照我们的意愿写入日志,我们如何才能让这段代码与桥接一起工作。 class可用。

直到 Log4j 2.17.1,PropertyConfigurator 一直是 no-op。这将在即将发布的版本中改变(参见 source code):您的代码应该 无需任何更改

为了测试新版本,添加 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>

并将 log4j-1.2-api 的版本设置为 2.17.2-SNAPSHOT:

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

编辑:如果不能使用快照或者等待下一次发布,可以模拟PropertyConfigurator的行为如下:

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);