Eric Bergman-Terrell's Blog

How to Programmatically Read a Locked Log4Net Log File
November 6, 2007

I recently added log4net logging to this website. After configuring log4net and adding logging code the the web application, I immediately added a page to my administration site to display the log. Unfortunately, the initial code I wrote threw an exception because, not surprisingly, the log4net log file was locked.

The trick is to open the file in FileShare.ReadWrite mode:

...

protected string logFileText;

protected void Page_Load(object sender, EventArgs e)
{
    string path = Server.MapPath("~/logs/log.txt");

    using (FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
    using (StreamReader streamReader = new StreamReader(fileStream))
    {
        logFileText = streamReader.ReadToEnd();
    }
}

...
Keywords: Log4Net, logging, software development, .NET, file locking

Reader Comments

NameCommentURLDate/Time
LinusThe solution provided by Sunil is not the same and will not solve the same issues, as "MinimalLock" can still lock the file, as I already had that set and needed to stream.
 December 19, 2014
Sunil SharmaI found a better method to do this at: http://hoenes.blogspot.com/2006/08/displaying-log4net-log-file-on-aspnet.html
http://hoenes.blogspot.com/2006/08/displaying-log4net-log-file-on-aspnet.htmlFebruary 18, 2009
mr mOThank you sooo very much!
http://mokhan.caJuly 24, 2008

Comment on this Blog Post

Recent Posts

TitleDate
EBTCalc (Android) Version 1.53 is now availableMay 19, 2024
Vault 3 Security EnhancementsOctober 24, 2023
Vault 3 is now available for Apple OSX M2 Mac Computers!September 18, 2023
Vault (for Desktop) Version 0.77 ReleasedMarch 26, 2023
EBTCalc (Android) Version 1.44 is now availableOctober 12, 2021
Vault (Desktop) Version 0.72 ReleasedOctober 6, 2021
EBT Compass is Now Available for Android DevicesJune 2, 2021