servicelog4netlog4net-configuration

Stop log4net (or services) using a file when errors are not being placed in it


I have the following log4net config

<?xml version="1.0" encoding="utf-8" ?>
<log4net xmlns="urn:log4net">

  <appender name ="RollingFile" type="log4net.Appender.RollingFileAppender">
    <file value="C:\temp\Generator.log" />
    <appendToFile value="true" />
    <rollingStyle value="Size" />
    <maximumFileSize value="500KB" />
    <maxSizeRollBackups value="10" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date{DATE} %level %thread %logger - %message%newline" />
    </layout>
  </appender>
  <appender name ="GenerationErrors" type="log4net.Appender.FileAppender">
    <file type="log4net.Util.PatternString" value="c:\temp\GenerationErrors.log" />
    <appendToFile value="true" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date{DATE} %level %thread %logger - %message%newline" />
    </layout>
  </appender>
  <root>
    <appender-ref ref="RollingFile" />
    <level value="INFO" />
  </root>
  <logger name ="GPA.Module.Generate">
    <level value="INFO" />
    <appender-ref ref="GenerationErrors" />
  </logger>

  <logger name="PmuManagement">
    <level value="INFO" />
    <appender-ref ref="GenerationErrors" />
  </logger>

</log4net>

The first appender logs all errors for all of my processes and the second only logs a certain group of errors, as required.

I need to be able to delete the contents of the second log file on the fly however this isn't currently possible as the programme needs constant access to it to run (if you try and make any changes you get the "this file is in use by another programme" error.

Is there a way for log4net to only need access to the file when errors need to be written to it?

Or is there a more generic way to stop services/programmes needing access to file temporarily and allowing access again shortly after?

Thanks


Solution

  • I found this question here Intermittent log4net RollingFileAppender locked file issue and the answer is what I needed. I simply added <lockingModel type="log4net.Appender.FileAppender+MinimalLock" /> to my second appender.