Adsence750x90

Monday, August 24, 2009

Create Error Log in ASP.NET - Exception handling

How to log your errors in asp.net C#

There are many methods to log errors for example send errors via mail or keep in text file. This is an example to how to log errors in text file.

Class file to save Exception.

In this class there is one function ErrorLog parameter of error log is Exception
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;


public class LogError
{
public LogError()
{
public static void ErrorLog(Exception er)
{
try
{
string path = HttpContext.Current.Server.MapPath("errorlog.txt");
if (!System.IO.File.Exists(path))
{
using (System.IO.StreamWriter sw = System.IO.File.CreateText(path))
{
sw.WriteLine("Error :" + DateTime.Now.ToString());
sw.WriteLine(er.Source + er.Message + er.StackTrace);
sw.WriteLine("******************************************************");
}
}
else
{
using (System.IO.StreamWriter sw = System.IO.File.AppendText(path))
{
sw.WriteLine("Error :" + DateTime.Now.ToString());
sw.WriteLine(er.Source + er.Message + er.StackTrace);
sw.WriteLine("******************************************************");
}
}
}
catch
{
}
}
}

3 comments:

Anonymous said...

thank you man

SeeSharpWriter said...

Hello, this is a nice way to introduce ASP.NET exception logging in a file. But, in my opinion, .NET offers features such as generics and inheritance and polymorphism which can be utilized to write more reusable code. However, I have written little more advanced approach for doing that - it addresses object-oriented log messages, database logging and can be easily configured to log in file. If you seek little more OOP approach, you can check my post Creating C# Logger and please provide me with your feedback! The classes are freely available for download.

SeeSharpWriter said...

Your logging function is clean and simple, I commented it today earlier. I like your blog in general, whould you like us to exchange links between blogs ? Increased traffic is a benefit for both of us...