log4j2 运行时重新配置不起作用 - 创建了空文件

标签 log4j2

我正在尝试在运行时手动重新配置 log4j2,但部分成功。

相关代码如下:

package examples.test;

public class ABCImpl implements XYX{

    static Logger logger;

public void initialize(){
    LoggerContext ctx = null;
    Configuration config =  null;
    Map mp = null;

    ctx = (LoggerContext) LogManager.getContext(false);
        config = (Configuration)ctx.getConfiguration();
    mp = config.getAppenders();
    System.out.println("***<Provider o/p follows> Before logger re-configuration:");
        System.out.println("\tAppenders:" + mp.keySet());

    //reconfiguration attempt - starts
    try{
        URI configuration = this.getClass().getResource("/log4j2.xml").toURI();
        ctx  = Configurator.initialize(this.getClass().getName(), null, configuration);
    }catch(Exception e){
        System.out.println("\t-------Exception encountered-------");
        e.printStackTrace();
    }

        config = (Configuration) ctx.getConfiguration();
    mp = config.getAppenders();
    System.out.println("***<Provider o/p follows> After logger re-configuration:");
    System.out.println("\tAppenders:" + mp.keySet());

    //reconfiguration attempt - ends

    logger = LogManager.getLogger(this.getClass().getName());
}

public void myBusinessMethod(){
        logger.info("Entry..............");
        logger.info("Exit..............");
    }
}

这个类实际上是一个 jar 文件的一部分,并在应用程序服务器中运行它,这保证了我的 initialize 方法会在我的类被实例化后立即被调用。

这是我的 log4j2.xml,我已将其打包到 jar 的根目录中:

<?xml version="1.0" encoding="UTF-8"?>

    <!-- Don't forget to set system property
    -DLog4jContextSelector=org.apache.logging.log4j.core.async.AsyncLoggerContextSelector
    to make all loggers asynchronous. -->

<Configuration status="info">
    <Appenders>
    <!-- Async Loggers will auto-flush in batches, so switch off immediateFlush. -->
        <RollingRandomAccessFile name="Appender1" fileName="servers/${sys:weblogic.Name}/logs/Auditing_${sys:weblogic.Name}.log" immediateFlush="true" append="false" filePattern="servers/${sys:weblogic.Name}/logs/archive/Auditing_${sys:weblogic.Name}-%d{yyyy-MM-dd-HH}-%i.log.gz">
            <PatternLayout>
                <Pattern>%d %p %c{1.} [%t] %m %ex%n</Pattern>
            </PatternLayout>
            <Policies>
                <TimeBasedTriggeringPolicy interval="1" modulate="true"/>
                <SizeBasedTriggeringPolicy size="250 MB"/>
            </Policies>
            <DefaultRolloverStrategy max="20"/>
        </RollingRandomAccessFile>
        <Async name="Async1">
            <AppenderRef ref="Appender1"/>
        </Async>
    </Appenders>
    <Loggers>
        <Logger name="examples.test.ABCImpl" level="info" includeLocation="false" additivity="false">
            <AppenderRef ref="Appender1"/>
        </Logger>
        <Root level="info" includeLocation="false">
            <AppenderRef ref="Appender1"/>
        </Root>
    </Loggers>
</Configuration>

问题是即使创建了日志文件,但其中没有记录任何内容。我得到的标准输出中的输出是:

ABCImpl.initialize
        activeHandlerEntries.length=1
***<Provider o/p follows> Before logger re-configuration:
        Appenders:[Console]
***<Provider o/p follows> After logger re-configuration:
        Appenders:[Async1, Appender1]

如果我使用 -Dlog4j.configurationFile=file:SOME_PATH_OUTSIDE_JAR/log4j2.xml<,只是为了确保我的 log4j2.xml 和这段代码在没有运行时重新配置的情况下是可以的 日志按预期填充。

请帮忙。

最佳答案

我想知道,如果通过以下方式导出初始化上下文

ctx = (LoggerContext) LogManager.getContext(false);

可能是问题所在,因为您必须访问“当前”上下文

ctx = (LoggerContext) LogManager.getContext(true);

根据 the Log4j2 API .我非常感谢您的澄清,因为我也在尝试以编程方式配置 Log4J2。

关于log4j2 运行时重新配置不起作用 - 创建了空文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22474503/

相关文章:

java - 在运行时更新 log4j2 模式

java - Spring Sleuth,Log4j2不同服务中的不同跟踪ID

java - Log4j2 不会在运行时更改日志记录级别

mysql - org.apache.commons.dbcp.DelegatingPreparedStatement.setNString(ILjava/lang/String;)V

java - 切换到log4j2后如何修复javax.xml.parsers.ParserConfigurationException?

java - 如何从外部 Maven 依赖项禁用 Log4j 配置?

java - Log4j 2 : can't use the ContextMapLookup in RollingFileAppender fileName and filePattern

java - 带有滚动文件附加程序的 Log4j2 AsyncLogger 不显示文件行号

log4j2 - 如何在调用 LogManager.shutdown() 后重新启动 log4j2?

java - log4j2-slf4j-impl 重复依赖项