How do I make log4j create log files on demand only?

I had the same problem, so I have extended the standard FileAppender class and I have created a new LazyFileAppender that is a FileAppender that lazily initialize the log file(creates it only when the first write operation happens).

The LazyFileAppender and some other additions to the standard log4j library can be found into a simple library that I have created : log4j-additions .

You can look at the source to develop your own extension or you can use it as is ...


The file appenders have no option to lazily create the log files - the setFile method automatically creates the file if it doesn't already exist: ostream = new FileOutputStream(fileName, append);

You'll have to extend the appender and overwrite the file initialisation code yourself to get the behaviour you're after.


In Log4j 2, both FileAppender and RollingFileAppender has the parameter "createOnDemand" which can be used to configure to create the log file only when a log event passed to the appender.

Example:

<RollingFile name="LogFile" fileName="test.log" filePattern="test-%i.log.gz" createOnDemand="true">
    <Policies>
        <SizeBasedTriggeringPolicy size="1MB"/>
    </Policies>
    <DefaultRolloverStrategy max="5"/>
</RollingFile>

More details here: https://logging.apache.org/log4j/2.x/manual/appenders.html#RollingRandomAccessFileAppender

Tags:

Log4J