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
Java Programming Tip: SWT Photo Frame ProgramOctober 31, 2016
Vault 3 (Desktop) Version 1.63 ReleasedSeptember 9, 2016
"Compliance with Court Orders Act of 2016"April 9, 2016
Disable "Visual Voicemail" on Android / T-MobileJanuary 17, 2016
IPv6 HumorDecember 10, 2015
Java Programming Tip: Specify the JVM time zoneDecember 7, 2015
Node.js / Express Programming Tip: Detect and Fix Memory LeaksOctober 27, 2015