Non-partisan software developer

Saturday, August 12, 2006

Displaying a Log4Net log file on an ASP.NET website

I wrote a simple web page to display the log file in a textarea from a data synchronization application that logged all it's juicy details to a Rolling log file.

I fired up the page to see my creation and it worked... until the sync service was fired up and started writing to the log file. After that the blasted page just threw a IO exception at me--another process has an exclusive lock on the file and I can't READ it! Turns out it's the default locking mode for FileAppenders but you can configure whatever you are comfortable with.

<appender name=\"RollingFile\" type=\"log4net.Appender.RollingFileAppender\">
<layout type=\"log4net.Layout.PatternLayout\">
<conversionPattern value=\"%d [%t] %-5p %c{1} - %m%n\" />
</layout>
<file value=\"Application.log\" />
<appendToFile value=\"true\" />
<maximumFileSize value=\"500KB\" />
<maxSizeRollBackups value=\"5\" />
<lockingModel type=\"log4net.Appender.FileAppender+MinimalLock\" />
</appender>

The element configures the Appender to use a MinimalLock which only will acquire a lock while it's writing. It appears that it also uses FileShare.Read which will not lock others from just reading it.

It's amazing that this information was so hard to come by, or maybe I was just having a bad google day. At anyrate I thought I'd be a good netcitizen and blog about it so hopeful some poor sap can find this and speed up the troubleshooting--even if that poor sap is me :P

6 comments:

Michael D. said...

You saved me about an hour with this post. Thanks!

Anonymous said...

I was a poor sap who needed this today. Thanks!

lucky said...

OMG, thank a lot
u save my life :P

Infoconex said...

I came across this same problem and one solution suggested was copying to another file the contents and then opening the temporary file. That did not seem elegant. Also as you suggested you can also change it to minimal lock (but I understand that has performance implications) also I think it would fail if you tried to read it when it was being written to.

I found the ultimate solution I believe and posted a blog entry on it.

http://coding.infoconex.com/post/2009/04/How-do-I-open-a-file-that-is-in-use-in-C.aspx

DominLondon said...

As Infoxconex mentioned, MinimalLock produces terrible performance if you are writing large amounts of data. This was causing me all sorts of performance problems in the application i work on. For example, With minimal lock it took 55 second to write 40000 log messages (1234567890123456789012345678901234567890). When i removed the +MinimalLock it took less than 1 second! So be warned if you need performance then dont use MinimalLock.

Cheers,

zeltera said...

Thanks. You helped me a lot.