Log file is 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 write something to it, but it is still empty. When I try to delete this file, the OS told me that it is being used (if the application is currently running), but even if I stop the application, the file is still empty.

So, what settings should be changed so that they work correctly?

+6
source share
2 answers

I suspect that the asynchronous log is not enabled correctly. Starting with beta-9, Async Loggers cannot be included in the XML configuration, you must set the Log4jContextSelector system property to "org.apache.logging.log4j.core.async.AsyncLoggerContextSelector" .

The reason you don't see anything in the log is because your log messages are still in the buffer and have not yet been flushed to disk. If you enable Async Loggers, the log messages will be automatically deleted to disk.

+4
source

I use a cleaner and lighter solution.

fooobar.com/questions/957702 / ...

Add a file called log4j2.component.properties to your classpath. This can be done in most maven or gradle projects by storing 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 try to read the system property first. If the system property is NULL, then it defaults to the values ​​stored in this file.

+2
source

Source: https://habr.com/ru/post/957700/


All Articles