Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

log file empty when using log4j2

I use log4j2 in my project something like this:

    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?

like image 864
silent_coder Avatar asked Nov 08 '13 18:11

silent_coder


2 Answers

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".

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.

like image 176
Remko Popma Avatar answered Oct 19 '22 23:10

Remko Popma


I share a cleaner and easier solution.

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

Add a file named log4j2.component.properties to your classpath. This can be done in most maven or gradle projects by saving it in 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. If the system property is null, then it will fall back to the values stored in this file by default.

like image 29
Davideas Avatar answered Oct 20 '22 01:10

Davideas