Log4net :Writing a log file to the same directory from multiple running instances of a program.

Alex van Buitenen, mei 2009

This article applies to Log4net version 1.2.10.0.

Problem description.

I want to write a log file to a fixed-name directory.
Multiple instances of the program are running at the same time (possibly by the same user).

When writing to the same log file, either:

Attempt to solve problem using a RollingFileAppender.

The log4net documentation gives an example to roll a log file once per program execution:

<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
    <file value="log/log.txt" />
    <appendToFile value="false" />
    <rollingStyle value="Size" />
    <maxSizeRollBackups value="-1" />
    <maximumFileSize value="50GB" />
    <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%d{dd-MM-yyyy HH:mm:ss} [%X{user}] - %message%newline" />
    </layout>
</appender>

This works fine when one instance of a program is running, but the active log file is "log.txt" (backups get renamed to log.txt.1, log.txt.2 etc.)
So I keep the problem of writing to the same file from within multiple instances of my program.

Tried to solve this by adding <staticLogFileName value="false" />
Log4Net keeps writing to "log.txt", so added: <countDirection value = "1">

Now Log4Net writes to "log.txt.0" the first time it runs.
The second time it runs it says:

"log4net:ERROR RollingFileAppender: INTERNAL ERROR. Append is False but OutputFile [G:\Study\QuickStartLog4Net\QuickStartLog4Net\bin\Debug\log\log.txt.0] already exists."

I tried several combinations the Rolling FileAppender allows, but none gave the desired result.
 

Working Solution.

I did find a solution that uses the processid in a filename, so now I can write to different logfiles in the same directory:

<appender name="AppenderWithProcessId" type="log4net.Appender.FileAppender">
    <file type="log4net.Util.PatternString">
        <conversionPattern value="log/%date{yyyyMMMdd} processid[%processid].txt" />
    </file>
    <appendToFile value="false" />
    <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%d{dd-MM-yyyy HH:mm:ss} [%X{user}] - %message%newline" />
    </layout>
</appender>
 

The drawback of this solution is that new files keep being written, while the RollingFileAppender has maxSizeRollBackups to limit the number of files.