.net – Need advice on server side logging with log4net

log4netnet

We are using log4net for our server side logging. The problem we are facing is with the FileAppender. Here is our log4net section in the app.config file:

  <log4net xsi:noNamespaceSchemaLocation="http://csharptest.net/downloads/schema/log4net.xsd"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <appender name="MainAppender" type="log4net.Appender.FileAppender">
      <lockingMode type="log4net.Appender.FileAppender+MinimalLock" />
      <file value="${TMP}\Shunra.Infra.Test.Host.log" />
      <appendToFile value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
      </layout>
    </appender>
    <root>
      <level value="ERROR" />
      <appender-ref ref="MainAppender" />
    </root>
  </log4net>

The thing is that when multiple threads write to the log file, log4net sometimes fails to acquire the lock to the file, because another thread is logging at this same moment. The problem manifests itself in a first chance IOException handled by log4net internally.

I am not sure that we are using log4net correctly in this case and would like to get an advice on how to improve its configuration.

Thanks.

Best Answer

With MinimalLock you instruct the FileAppender to only aquire a lock to the log file when it writes log messages and immediately release the lock when done writing. This means that other processes will have the opportunity to aquire a lock to the log file in between log flushes.

The fact that your log file is located in the TEMP folder (where a lot of processes do their temporary work) increases the risk of other processes "tampering" with your log file.

My advice in your scenario is:

  1. Use RollingFileAppender. This is a more scalable appender when it comes to handling large log amounts.
  2. Create a dedicated folder for your log files.
  3. Use default ExclusiveLock to improve log performance
Related Topic