Slf4j / log4j:在运行时添加的FileAppender不起作用

时间:2016-03-31 07:27:36

标签: java log4j slf4j log4j2

我正在使用log4j 2.5和slf4j 1.7.19。这是我的log4j2.xml:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
    <Properties>
        <Property name="log-path">D:/opt/verzeichnis-shop/logs/</Property>
    </Properties>

    <Appenders>

        <Console name="A1" target="SYSTEM_OUT">
            <PatternLayout pattern="[%-5p][%15.15t]%d{HH:mm:ss,SSS} %-6r ..%35.35c:%-4L - %m%n"/>
        </Console>


        <RollingFile name="A2" fileName="${log-path}/vzshop.log" filePattern="${log-path}/vzshop_%d{yyyy-MM-dd}.log">
            <PatternLayout>
                <pattern>[%-5p][%15.15t]%d{HH:mm:ss,SSS} %-6r ..%35.35c:%-4L - %m%n</pattern>
            </PatternLayout>
            <Policies>
                <TimeBasedTriggeringPolicy interval="1" modulate="true"/>
            </Policies>
        </RollingFile>
    </Appenders>

    <Loggers>
        <Logger name="de.mycompany.vzshop" level="debug" additivity="false">
            <AppenderRef ref="A1"/>
            <AppenderRef ref="A2"/>
        </Logger>

        <Root level="info">
            <AppenderRef ref="A1"/>
            <AppenderRef ref="A2"/>
        </Root>
    </Loggers>

</Configuration>

我正在初始化它:

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

现在我想在运行时添加FileAppender:

public static void appendBookLogger(String bookDir, String uuid) {

    LoggerContext loggerContext = (org.apache.logging.log4j.core.LoggerContext) LogManager.getContext(false);
    String path = bookDir + File.separator + uuid + ".log";
    logger.info("Adding appender: " + path);

    final Configuration config = loggerContext.getConfiguration();
    PatternLayout layout = PatternLayout.createLayout("[%-5p][%15.15t]%d{HH:mm:ss,SSS} %-6r ..%35.35c:%-4L - %m%n", null, config, null,
        null,false, false, null, null);
    Appender appender = FileAppender.createAppender(path, "false", "false", "File", "true",
        "false", "false", "4000", layout, null, "false", null, config);
    appender.start();

    org.apache.logging.log4j.core.Logger rootLogger = loggerContext.getRootLogger();
    rootLogger.addAppender(appender);
    logger.info("Appender added.");
}

不幸的是,这不起作用。正在创建日志文件(路径)但仍为空。我希望包含最后一个日志语句(“Appender added。”)。 我根本没有收到任何错误消息。

你知道这里可能出现什么问题吗?

0 个答案:

没有答案