Error Logging using ASP.NET 2.0

Posted by: Suprotim Agarwal , on 4/24/2008, in Category ASP.NET
Views: 308806
Abstract: Errors and failures may occur during development and operation of a website. ASP.NET 2.0 provides tracing, instrumentation and error handling mechanisms to detect and fix issues in an application. In this article, we will adopt a simple mechanism to log errors and exceptions in our website.
Error Logging using ASP.NET 2.0
 
This article has been republished with a few minor changes. Note: The code demoed in this article is for a small intranet application and shows a very simple error logging mechanism. It should not be used in production apps or sites with multiple access. If you plan to use error logging in a busy site, explore Elmah or Log4Net.
Errors and failures may occur during development and operation of a website. ASP.NET 2.0 provides tracing, instrumentation and error handling mechanisms to detect and fix issues in an application.
In this article, we will adopt a simple mechanism to log errors and exceptions in our website. We will be using a mechanism where the user will be redirected to a separate page whenever an error is encountered in the application. Simultaneously, the error will get logged in a text file on the server. The error file will be created on a daily basis, whenever the error is encountered. Having said that, let us now see some code.
Step 1: Start by creating an Error folder where all errors will be logged. Right click the website > New Folder. Rename the folder to “Error”. Also add a web.config file, if one does not already exist in your site. Right click the website > Add New Item > Web.config.
Step 2: Now we will create the error handler code. To do so, right click your website > Add New Item > select Class. Rename the class to ‘ErrHandler.cs’ and click on ‘Add’. When you do so, you will be prompted with a message to place the class in ‘App_Code’ folder. Accept the message to place the class in the 'App_Code' folder.
Step 3: Now let us add functionality to the ErrHandler class. This class will accept the error message and write the message in a text file. One text file will be created for each day. If the text file already exists, the message will be appended to the text file. If not, a new text file will be created based on today’s date and error message will be written in it.
The code will look similar to the following:
C#
/// Handles error by accepting the error message
    /// Displays the page on which the error occured
    public static void WriteError(string errorMessage)
    {
        try
        {
            string path = "~/Error/" + DateTime.Today.ToString("dd-mm-yy") + ".txt";
            if (!File.Exists(System.Web.HttpContext.Current.Server.MapPath(path)))
            {
                File.Create(System.Web.HttpContext.Current.Server.MapPath(path)).Close();
            }
            using (StreamWriter w = File.AppendText(System.Web.HttpContext.Current.Server.MapPath(path)))
            {
                w.WriteLine("\r\nLog Entry : ");
                w.WriteLine("{0}", DateTime.Now.ToString(CultureInfo.InvariantCulture));
                string err = "Error in: " + System.Web.HttpContext.Current.Request.Url.ToString() +
                              ". Error Message:" + errorMessage;
                w.WriteLine(err);
                w.WriteLine("__________________________");
                w.Flush();
                w.Close();
            }
        }
        catch (Exception ex)
        {
            WriteError(ex.Message);
        }
 
    }
VB.NET
''' Handles error by accepting the error message
    ''' Displays the page on which the error occured
    Public Shared Sub WriteError(ByVal errorMessage As String)
        Try
            Dim path As String = "~/Error/" & DateTime.Today.ToString("dd-mm-yy") & ".txt"
            If (Not File.Exists(System.Web.HttpContext.Current.Server.MapPath(path))) Then
                File.Create(System.Web.HttpContext.Current.Server.MapPath(path)).Close()
            End If
            Using w As StreamWriter = File.AppendText(System.Web.HttpContext.Current.Server.MapPath(path))
                w.WriteLine(Constants.vbCrLf & "Log Entry : ")
                w.WriteLine("{0}", DateTime.Now.ToString(CultureInfo.InvariantCulture))
                Dim err As String = "Error in: " & System.Web.HttpContext.Current.Request.Url.ToString() & ". Error Message:" & errorMessage
                w.WriteLine(err)
                w.WriteLine("__________________________")
                w.Flush()
                w.Close()
            End Using
        Catch ex As Exception
            WriteError(ex.Message)
        End Try
 
    End Sub
That was our ErrHandler class. We will now see how to use this Error Handler class and handle errors at the page level as well as at the application level.
Handling errors at Page Level
In the Default.aspx, drag and drop a button from the toolbox. Rename this button to btnError and set the Text as ‘Throw Handled Exception’. Here we will throw an exception. Since we have a catch block defined, the exception will be caught and the error will be logged in the Error folder. Since a text file with today’s date, does not exists, a new text file will be created by the code.
The button click handler will look similar to the following:
C#
protected void btnHandled_Click(object sender, EventArgs e)
    {
        try
        {
            throw new Exception("Sample Exception");
        }
        catch (Exception ex)
        {
            // Log the error to a text file in the Error folder
            ErrHandler.WriteError(ex.Message);
        }
    }
VB.NET
Protected Sub btnHandled_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnHandled.Click
        Try
            Throw New Exception()
        Catch ex As Exception
            ' Log the error to a text file in the Error folder
            ErrHandler.WriteError(ex.Message)
        End Try
    End Sub
Now with the code in place, run the application and click on the button. Since we have handled the error and logged the exception in our code, you will not notice anything when the button is clicked. However, close the application and refresh the Error folder. You will see a new text file created with today’s date. The exception has been logged successfully as shown below. The date and time will differ on your machine.
Log Entry :
01/11/2008 23:33:46
Error in: http://localhost:51087/ErrorHandling/Default.aspx. Error Message:Sample Exception
__________________________
Redirecting users on unhandled errors
Let us see how to catch unhandled errors and redirect the user to a different page, whenever such an unhandled error occurs at the application level.
To catch unhandled errors, do the following. Add a Global.asax file (Right click project > Add New Item > Global.asax). In the Application_Error() method, add the following code:
C#
 void Application_Error(object sender, EventArgs e)
    {
        // Code that runs when an unhandled error occurs
        Exception objErr = Server.GetLastError().GetBaseException();
        string err = "Error in: " + Request.Url.ToString() +
                          ". Error Message:" + objErr.Message.ToString();
        // Log the error
        ErrHandler.WriteError(err);       
    }
VB.NET
Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
        ' Code that runs when an unhandled error occurs       
        Dim objErr As Exception = Server.GetLastError().GetBaseException()
        Dim err As String = "Error in: " & Request.Url.ToString() & ". Error Message:" & objErr.Message.ToString()
        ' Log the error
        ErrHandler.WriteError(err)
    End Sub
We capture the error using the Server.GetLastError(). Now to redirect users to a different page whenever an unhandled error occurs, open your web.config file and locate the <customErrors> tag and uncomment it. After removing the comment, the tag will look similar to the following code:
<!--
            The <customErrors> section enables configuration
            of what to do if/when an unhandled error occurs
            during the execution of a request. Specifically,
            it enables developers to configure html error pages
            to be displayed in place of a error stack trace.        -->
 
                  <customErrorsmode="RemoteOnly"defaultRedirect="GenericErrorPage.htm">
                        <errorstatusCode="403"redirect="NoAccess.htm" />
                        <errorstatusCode="404"redirect="FileNotFound.htm" />
                  </customErrors>
Now change:
 mode="RemoteOnly"tomode="On"
defaultRedirect="GenericErrorPage.htm" to defaultRedirect="ErrorPage.aspx"
The modified code will now look like this:
<customErrorsmode="On"defaultRedirect="ErrorPage.aspx">
                        <errorstatusCode="403"redirect="NoAccess.htm" />
                        <errorstatusCode="404"redirect="FileNotFound.htm" />
                  </customErrors>
This configuration will now redirect the user to an Error page when an error occurs. Let us create this error page and display some message to the user.
Right Click Project > Add New Item> Create a new ErrorPage.aspx page in the application and display a sample message on the page informing the user that an error has occurred.
To test our functionality, go back to Default.aspx, add another button and rename it to btnUnhandled and set its Text property to ‘Throw Unhandled Exception’. Here instead of throwing the exception as we did for ‘btn_Error’, we will introduce a ‘Divide By Zero’ exception and not handle it. Observe that there is no try catch block as shown below. So when the error occurs, the user will be redirected to the ‘ErrorPage.aspx’ as a result of the changes made in our web.config file.
C#
protected void btnHandled_Click(object sender, EventArgs e)
    {
        try
        {
            throw new Exception("Sample Exception");
        }
        catch (Exception ex)
        {
            // Log the error to a text file in the Error folder
            ErrHandler.WriteError(ex.Message);
        }
    }
VB.NET
Protected Sub btnUnhandled_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUnhandled.Click
        Dim i As Integer = 1
        Dim j As Integer = 0
        Response.Write(i \ j)
    End Sub
 
Run the application and click on the ‘Throw Unhandled Exception’ button. You will observe that the user will be automatically redirected to the Error Page and the error will be logged in the Error folder. Well that’s it.
In this article, we saw how to implement a simple error logging system in our application. Logging errors can be very useful and helps us detect errors during development and operation of a website. ASP.NET also provides some advanced options titled under ‘Health Monitoring’ where the errors can be stored in Sql Server or even emailed to the administrator based on the criticality of it.
I hope this article was useful and I thank you for viewing it.  Download the source code of the application over here.

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for Sixteen consecutive years. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.

Get in touch with him on Twitter @suprotimagarwal or at LinkedIn



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by paul on Wednesday, January 16, 2008 11:56 PM
Good article.
Comment posted by EB on Sunday, January 27, 2008 9:17 AM
Paul: Thank you very much! your article is very valuable to me and your instruction on it is very clear. Great! very well for a 5(five) stars!
Comment posted by EB on Sunday, January 27, 2008 9:23 AM
Agarwal: Thank you very much! your article is very valuable to me and your instruction on it is very clear. Great! very well for a 5(five) star rating! Sorry I got your name wrong the first time.
Comment posted by sandhya on Sunday, January 27, 2008 1:12 PM
Excellent and easy to understand and implement. :)
Comment posted by Suprotim Agarwal on Tuesday, January 29, 2008 12:26 PM
Thanks for the comments, sandhya and EB.
Comment posted by Jo.Net on Sunday, March 30, 2008 4:34 PM
Bril Thanks

One thing

Dim path As String = "~/Error/" & DateTime.Today.ToString("dd-mm-yy") & ".txt"
The mm is for minute with me and should be MM for month.  Maybe "yyyy-MM-dd"  would be better as the error files could then be sorted by name
Comment posted by Jo.Net on Monday, March 31, 2008 1:35 PM
Bril Thanks

One thing

Dim path As String = "~/Error/" & DateTime.Today.ToString("dd-mm-yy") & ".txt"
The mm is for minute with me and should be MM for month.  Maybe "yyyy-MM-dd"  would be better as the error files could then be sorted by name
Comment posted by DotNetYuppie on Thursday, April 24, 2008 2:42 PM
Great article -- I wrote one that focused a little more on the recording of errors a few days ago (http://dotnetyuppie.com/2008/04/22/handling-and-recording-exceptions-in-net/)

I understand you've created the basic framework here, but the Ex.Message and URL usually aren't sufficient enough to track down an error or bug.  You might also consider adding in Ex.StackTrace so you can get the line number of the code that threw an exception.
Comment posted by Satya on Sunday, April 27, 2008 12:15 PM
It's a very veyr good share. Thanks for sharing knowledge.
Comment posted by c.diaz on Thursday, May 1, 2008 7:28 AM
The problem with this error logging code is that it writes to a text file that could be in use at any moment. If the file is being written to by another user it will be locked and therefore another error will be generated when attempting top write to it. Am I right or I am missing something?
Comment posted by Suprotim Agarwal on Saturday, May 3, 2008 7:20 AM
CDiaz: It's not the user who opens and writes the file. It's asp.net fw which does so.
Comment posted by Kunle on Wednesday, May 7, 2008 10:58 AM
C.Diaz is right. If you have many users using the app and say there are 4 errors thrown at the same time, it looks like the error handling mechanism would go into an into a loop because while trying to write it throws an error which will cause it to try to write the error to file again and so on.... potential for an inifite loop if the file becomes corrupt. But its a good start for error handling. Good article
Comment posted by Ashok on Monday, May 26, 2008 7:18 AM
Nice one
Comment posted by Geosync on Tuesday, June 17, 2008 5:43 PM
I've searched a long time for a simple explanation about this!  Yours wins the prize.  Thank you.
Comment posted by David on Tuesday, June 17, 2008 7:14 PM
Is this not re-inventing the wheel when you have some really good frameworks that have already though of the concurrency problems and offer far greater flexability... look at Log4Net its even free ;).  You can write to files, databases, event logs, setup things such as rolling file appenders.... the list goes on!  You code does a fraction of that and you have wasted your time in my opinion!  
Comment posted by David on Tuesday, June 17, 2008 7:18 PM
Why did you choose to send just the error message as well?  Surly its better to pass the Exception to the message.  Then later on if you want to include the stack trace its easy to do so??

"static void WriteError(string errorMessage)"
Comment posted by Eric Fan on Tuesday, June 17, 2008 8:18 PM
Agree with David.

In definition of WriteError() method. You call WriteError() again when catch an exception. I think this will bring problem. If an exception is raised because file can't be open or created, call WriteError() again will crash your system.


  
Comment posted by Pavan Kumar on Wednesday, June 18, 2008 12:43 AM
I personally think its a good article to start off.
Comment posted by Dario on Wednesday, June 18, 2008 8:59 AM
Hello, the article is excellent and easy to understand, just one thing. When you show the c# exmaple "Divide By Zero" exception and not handle it, is not apropiate example.

see you round
Dario from Argentina.
Comment posted by Henrik on Wednesday, June 18, 2008 11:15 AM
Excellent work
you've got a five man!
Comment posted by DarthSwian on Wednesday, June 18, 2008 12:02 PM
We're actually using Log4Net to trap code errors and ELMAH to trap general site errors and put it into the same table as Log4Net data. Its been a very good system and all information is in one central database, sortable by application id
Comment posted by DarthSwian on Wednesday, June 18, 2008 12:35 PM
We're actually using Log4Net to trap code errors and ELMAH to trap general site errors and put it into the same table as Log4Net data. Its been a very good system and all information is in one central database, sortable by application id
Comment posted by Kevin-Lv on Thursday, June 19, 2008 1:54 AM
ELMAH is really good choice.
Comment posted by Suprotim Agarwal on Thursday, June 19, 2008 10:19 AM
David: Thanks for the suggestion. A good one.

Darth, Kevin: Yes for big enterprise apps, I agree. The sample I have given would suit small scale apps which needs error handling to be quickly built and customized. Thanks for letting viewer know about ELMAH.

Everyone else: Thanks a lot for your comments.
Comment posted by Phong Nguyen on Thursday, June 19, 2008 11:01 AM
This is a great stuff. The option that you could considering is healthMonitoring feature in asp.net
Comment posted by Phong Nguyen on Thursday, June 19, 2008 12:13 PM
This is a great stuff. The option that you could considering is healthMonitoring feature in asp.net
Comment posted by ramesh on Monday, June 23, 2008 12:07 AM
Good effort. But not good for web applications. Multiple application cannot access the same file at the same time.
Comment posted by Namitha on Monday, June 23, 2008 4:58 PM
Very nice & easy understanding of all the required features.
Comment posted by Raghu on Monday, June 23, 2008 5:36 PM
I think this code does not handle multiple users. If multiple worker process threads tries to write this error log then error log will throw an IO error.
Comment posted by Narayan on Monday, June 23, 2008 5:38 PM
amending raghu's comment, it will go to an infinite loop and hangs the server when log error throws exception. I would give 2 ** for this.
Comment posted by lee on Tuesday, June 24, 2008 12:25 AM
jsdlfsdjlfsjdlfads
Comment posted by Arvind Mewara on Tuesday, June 24, 2008 2:47 AM
awesome dude.
very nice and help full article
Comment posted by Jason Kiesel on Tuesday, June 24, 2008 5:16 PM
Log4Net is a great (and FREE) logging tool for ASP.NET. It's relatively simple to integrate and has a wealth of logging options (files, email, sql, etc.) Why reinvent the wheel?
Comment posted by Ashi on Wednesday, June 25, 2008 9:34 AM
Nice job .. its really a good article to understand the concepts thanks a ton.. keep updating article like this.. thanks again...
Comment posted by Bruno Caimar on Wednesday, June 25, 2008 12:55 PM
Sorry per criticism but... Why you don't use log4net or Logging application block instead of create a new one ? It's not clear for me in the article that it's just a sample or for small apps.
Comment posted by Suprotim Agarwal on Wednesday, June 25, 2008 10:57 PM
Jason, Bruno: Thanks for your comments. I understand and acknowledge that Log4Net is a great tool. However this article is solely meant to educate users of how they can 'start-off' with by building a simple error logging mechanism. As the need grows, the team can shift to something more concrete and full of functionality (like Log4Net). Ironically, I used this simple technique for a client who just was not ready to use a 3rd party tool to log errors, as they did not have good experiences with it in the past and would not budge  :)
Comment posted by Joe on Friday, June 27, 2008 11:14 AM
This code has a concurrency problem. It will fail when multiple users are your site and your try to write the log at the same time.
Comment posted by shankar on Thursday, July 3, 2008 7:51 AM
This is a great stuff. The option that you could considering is healthMonitoring feature in asp.net
Comment posted by shankar Suresh on Thursday, July 3, 2008 7:53 AM
This is a great stuff. The option that you could considering is healthMonitoring feature in asp.net
Comment posted by Venkat on Thursday, October 9, 2008 11:51 AM
Nice and brief article explaining in detail to create a Error Log

Please Update the article with the Required namesapces

Imports System.IO
Imports System.Globalization

your article really helped me to update my website .
thanks for sharing
Comment posted by Venkat on Friday, October 17, 2008 10:46 AM
Needs a small correction in the Date part of the code

Replace "dd-mm-yy" with "dd-MM-yy"
Comment posted by Suprotim Agarwal on Wednesday, October 22, 2008 11:52 AM
Thanks Venkat for the tips!
Comment posted by Chinmaya on Wednesday, October 29, 2008 3:58 AM
Hi this is chinmaya i got lot of informaiton while reading this article
Comment posted by Prashant Akerkar on Tuesday, November 4, 2008 1:06 AM
Looks a Good Code of Creating a Error Logging File on Web Server machine . Just wanted to know by adding further code whether the error logging file created on the Web Server using System.Net.Mail Namespace or any other Email sending component can be send to Developers Website as a File attachment so that Developers  can check their email box for the Trapped exceptions and then later rectify these Bugs.

i.e Send a email to Developers website attaching the Error Logging Help on Day to Day Basis.

Thanks
Comment posted by Matt on Thursday, January 8, 2009 5:33 AM
Hi this is a nice article. You could do with changing the web.config custom error to 503 status code. This is a common mistake developers make. 4xx error status codes often cause google bots to remove a page from the index completely. This could be really really bad if you run a popular site. If you use a 503 error status code, the bot will be told to try again later instead. More people to do this rather than just sticking up a 403.
Comment posted by Suprotim Agarwal on Thursday, January 8, 2009 8:58 AM
Thanks for the cool tip Matt.
Comment posted by mingster on Thursday, January 8, 2009 11:50 AM
why not just log4net?
Comment posted by Suprotim Agarwal on Thursday, January 8, 2009 8:32 PM
Yes, log4net , ELMAH etc are all great tools. Read my comments written earlier to get the context of this article. Thanks.
Comment posted by Shakti SIngh Dulawat on Friday, January 9, 2009 3:09 AM
This is very nice example mention my you, this is helpful for programming logic.
Thanks
Shakti
<strong><a href="http://www.nextmvp.blogspot.com/" >www.nextmvp.blogspot.com</a></strong>
Comment posted by Matt on Sunday, January 11, 2009 10:32 AM
This code IS NOT thread safe and SHOULD NOT be used in production applications where ASP.Net worker pool thread count is greater than 1.  The code should utilize a lock(){} block and gracefully handle IO exceptions from inside the volatile code.
Comment posted by Kamran Shahid on Monday, January 12, 2009 6:33 AM
Matt can you please correctify the actual code [meant where should we palce lock]
Also does this code is also perfectly usable with ajax enabled web application ?
Comment posted by Suprotim Agarwal on Tuesday, January 13, 2009 12:26 AM
Matt: The article was never written to be used as a replacement of tools like Log4Net etc which suit well in production apps. My previous comments reflect that.

For those who still think that this code will suit production apps, the answer is no. The article was written almost a yr ago to demonstrate how we can quickly create error handling functionality and log errors in small scale apps.

However, Matt's point about utilizing lock() is a very important one and is well taken.

Kamran: Yes the code would work in ajax apps. However I am not sure what you mean by 'perfectly usable'
Comment posted by Varun on Friday, May 29, 2009 10:48 AM
Thanks, this code is just good. The article is not Search Engine friendly or may be i was unlucky not getting this article before.
Comment posted by Chris Martin on Wednesday, June 3, 2009 4:01 PM
This is code any amateur programmer would be able to write.  It's very dangerous to use on a live server.  It's not as impressive as many of you think.  It's amateur demonstration is all.  All it is is a function that takes a string and writes it to a file -- again, not very impressive.  
Comment posted by Suprotim Agarwal on Thursday, June 4, 2009 2:57 AM
Chris: Unfortunately you haven't read my previous comments (2 comments above yours) where I have clearly stated that this code is not meant for production apps.
Comment posted by yogesh on Saturday, August 22, 2009 5:48 AM
this code is just good for apps.thanks
Comment posted by sapna on Tuesday, October 20, 2009 4:18 AM
Please include logging in ASP.net using SQL server or DB2 etc..your article is very helpful but it will become more helpful if you add SQL server logging in this..
Comment posted by Josh on Friday, October 30, 2009 9:32 AM
Don't forget synchronization issues.  You should place a SyncLock block around file access because if two clients try to log at the same time, this code will fail.
Comment posted by Mrkraju on Wednesday, November 11, 2009 10:55 AM
Extraordinary concept which is mainly used for .net family
Comment posted by DotNetApplePie on Monday, November 16, 2009 3:23 PM
Is this thread safe?
Comment posted by suresh on Sunday, November 22, 2009 2:53 AM
Its really good and easy to learn Error Log concept.
Thanks...
Comment posted by Fritz on Tuesday, December 8, 2009 1:33 AM
Very bad sample; I am appalled at the number of amateurs who think this is great code.
Your WriteError() method ends in an infinite loop if it throws an exception.
Besides, catching and swallowing all exceptions is the worst of all error handling practices.
Comment posted by John on Monday, December 14, 2009 9:14 AM
You're having a laugh yeah?

This is absolutely awful.
Comment posted by Jahid on Monday, January 25, 2010 3:51 AM
This code is working fine if I host the application in the IIS of the development machine. But, whenever I host it in another machine, error log is not created. Anyone please help me...
Comment posted by Chethan on Friday, February 26, 2010 10:42 AM
Nice Article .... Thanks Very Much!!!
Comment posted by mani.pke on Monday, April 5, 2010 12:09 PM
Hi Suprotim Agarwal,  Nice educative article...  I plan to use it in the Production server because I may not get ELMAH and other stuffs in the clients server.  Can you send me a skeleton code on handling sync issues...  Thanks in advance...  mani.PKE at gmail dot com.
Comment posted by Suprotim Agarwal on Tuesday, April 6, 2010 11:15 PM
Mani.pke: This article code should strictly not be used on the production server. It is suitable for small intranet apps
Comment posted by John on Monday, July 26, 2010 1:21 PM
once I have found good article about logging functionality with full source. it supports log rolling, multy-destination, inner exception and so on... I have modified source code a little based on my requirements and use it in my third project. May be it helps somebody yet http://vitana-group.com/article/microsoft-.net/logging
Comment posted by Firoz Shaikh on Thursday, July 29, 2010 10:03 AM
It is working fine in developent machine but on server following error occurs "Server Application Unavailable"
Comment posted by Good really on Tuesday, October 19, 2010 1:06 AM
veryGood  Thanks alot
Comment posted by Pankaj on Tuesday, January 4, 2011 11:23 PM
Thanx a lot,
For such a neat and descriptive article,
You saved my time...
Comment posted by atilla.malas on Monday, January 10, 2011 8:08 AM
very good and clear. Like this a lot
Comment posted by Sanjay Bhakkad on Friday, February 11, 2011 3:43 AM
Very good example. Easy to learn. Good for beginner. But I am getting one error : "File has been modified outside the source editor!" What to do for it?
Comment posted by Sunil Jain on Sunday, May 1, 2011 7:48 AM
Perfect article for me. I got what I was googling for. Thanks for this article. I wanna to know if the application is having too much traffic then is there any performance issue related with this code written above?

Comment posted by Suprotim Agarwal on Tuesday, May 3, 2011 2:06 AM
Sunil: As mentioned at the start of this article, the code is written as a quick and dirty way to log information. For an internet site, use Elmah  or Log4net
Comment posted by Muhammad Umar on Monday, May 16, 2011 10:45 AM
Nice article.....
Comment posted by joe on Wednesday, June 1, 2011 11:03 AM
good article.  thanks a lot.
Comment posted by shilpa on Tuesday, June 21, 2011 7:50 AM
nice article with good n working example..
it helped me a lot..
thanks!!!
Comment posted by muthuvijayan S on Tuesday, July 19, 2011 1:37 AM
Hi really a nice article.
Am also write about error logging.
<a href='http://dotnetpgm.blogspot.com/2011/06/error-logging-in-aspnet.html'>Error Logging in Asp.net c#</a>

My Blog
<a href='http://dotnetpgm.blogspot.com'>Dotnet Blog</a>
Comment posted by zhandos on Friday, January 20, 2012 1:12 PM
thanks, helped me a lot.
Comment posted by Bhargavi on Saturday, June 2, 2012 6:08 AM
Code is very good
Really Thaks
Comment posted by Bhushan on Thursday, August 16, 2012 1:38 AM
Toooooooo good dude, it realy helps a lot
Comment posted by Murali on Monday, September 3, 2012 7:16 PM
Thanks. It helped me a lot.
Comment posted by Amit on Wednesday, September 19, 2012 3:27 AM
my code:
public static void WriteError(string errorMessage)
    {
        try
        {
            string path = "~/Error/" + DateTime.Today.ToString("dd-mm-yy") + ".txt";
            if (!File.Exists(System.Web.HttpContext.Current.Server.MapPath(path)))
            {
                File.Create(System.Web.HttpContext.Current.Server.MapPath(path)).Close();
            }
            using (StreamWriter w = File.AppendText(System.Web.HttpContext.Current.Server.MapPath(path)))
            {
                w.WriteLine("\r\nLog Entry : " + "{0}", DateTime.Now.ToString(CultureInfo.InvariantCulture));
                string err = "Error in: " + System.Web.HttpContext.Current.Request.Url.ToString() +
                              ". Error Message:" + errorMessage;
                w.WriteLine(err);
                w.WriteLine(HttpContext.Current.Session["userName"]);

                //------------------- IP ----------------------------
                string strHostName = "";

                IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(strHostName);
                IPAddress[] addr = ipEntry.AddressList;
                strHostName = System.Net.Dns.GetHostName();

                w.WriteLine("Host Name : " + strHostName + ". IP Address : " + addr[addr.Length - 1].ToString());
               // w.WriteLine(System.Web.HttpContext.Current.Request.UserHostAddress);
                //------------------- IP ----------------------------
                w.WriteLine("--------------------------------------");
                w.Flush();
                w.Close();
            }
        }
        catch (Exception ex)
        {
            WriteError(ex.Message);
        }

    }


when i am upload web application it give s an error Like HTTP Error 503. The service is unavailable(sevices is toped in iis). at login time b'coz i have put erroe message on wrong email and password.
Comment posted by kavitha.n on Wednesday, December 19, 2012 5:29 AM
very good example.but i want clear definition of error loging
Comment posted by deepu on Thursday, June 13, 2013 4:05 AM
thank u very much
Comment posted by sagar on Friday, February 28, 2014 12:18 AM
it's really nice artical
but i want write error with line no
which line in generate error
Comment posted by karthik S on Friday, March 27, 2015 12:15 AM
Old is gold,
this article is very usefull for me.

Thanks
Karthik