简体   繁体   English

使用log4j2时,日志文件为空

[英]log file empty when using log4j2

I use log4j2 in my project something like this: 我在我的项目中使用log4j2,如下所示:

    logger.log(Level.ERROR, this.logData);

My configuration file looks like this: 我的配置文件如下所示:

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


<Configuration status="ERROR" DLog4jContextSelector="org.apache.logging.log4j.core.async.AsyncLoggerContextSelector">
    <Appenders>
        <!-- Async Loggers will auto-flush in batches, so switch off immediateFlush. -->
        <RandomAccessFile name="RandomAccessFile" fileName="C:\\logs\\log1.log" immediateFlush="false" append="false">
            <PatternLayout>
                <Pattern>%d %p %c{1.} [%t] %m %ex%n</Pattern>
            </PatternLayout>
        </RandomAccessFile>
    </Appenders>
    <Loggers>
        <Root level="error" includeLocation="false">
            <AppenderRef ref="RandomAccessFile"/>
        </Root>
    </Loggers>

It creates my file, I log something to it, but it's still empty. 它创建了我的文件,我记录了它,但它仍然是空的。 When I trying to delete this file, OS told me that it in use (if app currently working), but even if I stop application, file still empty. 当我尝试删除此文件时,操作系统告诉我它正在使用(如果应用程序当前正在工作),但即使我停止应用程序,文件仍然是空的。

So which settings should I change to make it work correctly? 那么我应该更改哪些设置才能使其正常工作?

I suspect that asynchronous logging is not switched on correctly. 我怀疑异步日志记录没有正确打开。 As of beta-9 it is not possible to switch on Async Loggers in the XML configuration, you must set the system property Log4jContextSelector to "org.apache.logging.log4j.core.async.AsyncLoggerContextSelector" . 从beta-9开始,无法在XML配置中打开Async Logger,必须将系统属性Log4jContextSelector设置为"org.apache.logging.log4j.core.async.AsyncLoggerContextSelector"

The reason you are not seeing anything in the log is that your log messages are still in the buffer and have not been flushed to disk yet. 您在日志中没有看到任何内容的原因是您的日志消息仍在缓冲区中并且尚未刷新到磁盘。 If you switch on Async Loggers the log messages will be flushed to disk automatically. 如果您打开Async Loggers,日志消息将自动刷新到磁盘。

I share a cleaner and easier solution. 我分享一个更简洁的解决方案。

https://stackoverflow.com/a/33467370/3397345 https://stackoverflow.com/a/33467370/3397345

Add a file named log4j2.component.properties to your classpath. 将名为log4j2.component.properties的文件添加到类路径中。 This can be done in most maven or gradle projects by saving it in src/main/resources. 这可以在大多数maven或gradle项目中通过将其保存在src / main / resources中来完成。

Set the value for the context selector by adding the following line to the file. 通过将以下行添加到文件来设置上下文选择器的值。

Log4jContextSelector=org.apache.logging.log4j.core.async.AsyncLoggerContextSelector

Log4j will attempt to read the system property first. Log4j将首先尝试读取系统属性。 If the system property is null, then it will fall back to the values stored in this file by default. 如果系统属性为null,则默认情况下它将回退到此文件中存储的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM