Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emailing a log4net log as a System.Net.Mail.Attachment throws IOException (process locked)

I wanted to send the current log4net log as an email attachment using System.Net.Mail.Attachment but when I pass in the file path an IOException is thrown.

Attachment mailAttachment = new Attachment(logPath);

The process cannot access the file 'C:\Log\log4net.log' because it is being used by another process

The appender configuration looks like this:

<appender name="RootRollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
    <param name="File" value="C:\Log\log4net.log" />
    <param name="AppendToFile" value="true" />
    <param name="MaxSizeRollBackups" value="10" />
    <param name="MaximumFileSize" value="10024KB" />
    <param name="RollingStyle" value="Size" />
    <param name="StaticLogFileName" value="true" />
    <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="%date [%username|%thread] %-5level %logger: %message%newline" />
    </layout>
</appender>

Is there any way to get around this? Can I copy out the log file or somehow release it from the locking process?

like image 928
Ian R. O'Brien Avatar asked Jan 08 '13 18:01

Ian R. O'Brien


1 Answers

<appender name="FileAppender" type="log4net.Appender.FileAppender">
    <file value="${TMP}\log-file.txt" />
    <appendToFile value="true" />
    <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
    <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
    </layout>
</appender>

using <lockingModel type="log4net.Appender.FileAppender+MinimalLock" /> will tell log4net to only lock the file for a brief moment while it is doing the actual writing. There is a slight performance penalty, but allows you to do things such as add it as an attachment a lot easier.

Otherwise log4net will lock the file indefiniately while the process is running.

like image 113
Despertar Avatar answered Nov 15 '22 00:11

Despertar