Tuesday, June 28, 2011

Error Logging in C# Asp.net



Errors may occur during the development. Not only in the Web sites, it is in all the fields. Every coders may know which place the error will come.Some errors can be easily identified and get a solution easily.But some cases we cant identify what error and why this error is coming like this. For an good website we have to maintain the error log in the Application. So we can track the errors easily and fix the issues sooner.


In this post, we will see how to create a simple error log in our website. We will show an error has been occured message to the user. At the same time,we will log the error in a htm file. The html error file will be created with the name of current date. whenever the error is occurred, It will automatically update with the html file.


Types of errors

Syntax errors-(ex: we missed the semicolon at end of the statement).
Logical error-(ex: Converting a string to int).
Application error-(ex: may be the folder permission does not give to create a new file).

Download the project with full source code.

let us see steps,how to catch errors and log.

Step 1: Create a new folder named Logs and set write permission.

Step 2: Create a new ErrorPage.aspx and in that page write the Error has been occurred during process message in a Label.

Step 3: create a new class named General.cs and add the variables to use in the error log.

private string strDLLName, strErrorIn, strFileName, strFileLocation, strErrorMethodName, strErrorMessage, strLineNo, strException, strLogFormat;


Step 4: write the method GetErrorDetails as a return type void.
public void GetErrorDetails(Exception ex)
 {
 strException = ex.StackTrace.Trim().Remove(0, 3);
 string strDllInfo, strLocationInfo;
 if (strException.Contains(":") && strException.Contains(".") && strException.Contains("\\"))
 {
 strDllInfo = strException.Substring(0, strException.IndexOf('('));
 strLocationInfo = strException.Substring(strException.IndexOf(')'), (strException.LastIndexOf(':')) - strException.IndexOf(')')).Remove(0, 5);

 //Get the DLL Name
 strDLLName = strDllInfo.Substring(0, strDllInfo.Substring(0, strDllInfo.LastIndexOf('.')).LastIndexOf('.'));

 //Get the File Type & Name
 string strFileCheck = strLocationInfo.Substring(strLocationInfo.LastIndexOf('\\')).Remove(0, 1);
 string[] arrFileCheck = strFileCheck.Split('.');

 if (arrFileCheck.Length > 2)
 strErrorIn = "Page File";
 else
 strErrorIn = "Class File";
 strFileName = strFileCheck;

 //Get the Error File Location
 strFileLocation = "~\\" + strLocationInfo.Substring(AppDomain.CurrentDomain.BaseDirectory.Length);

 //Get the Error Method Name
 strErrorMethodName = strDllInfo.Substring(strDllInfo.LastIndexOf('.')).Remove(0, 1);

 //Get the Error Meassage
 strErrorMessage = ex.Message;

 //Get the Error Line No.
 strLineNo = strException.Substring(strException.LastIndexOf(':'), (strException.Length - strException.LastIndexOf(':'))).Remove(0, 6);
 }
 else
 {
 strDLLName = "-";
 strFileName = "-";
 strFileLocation = "-";
 strErrorMethodName = ex.ToString();
 strErrorIn = "Application Error";
 strLineNo = "-";
 strErrorMessage = ex.Message;
 }
 //Write the Error In ErroLog File
 WriteError(strDLLName, strErrorIn, strFileName, strFileLocation, strErrorMethodName, strErrorMessage, strLineNo);
 }

Step 5: Write the catched error in the html file
private void WriteError(string strDLLName, string strErrorIn, string strFileName, string strFileLocation, string strErrMethodName, string strErrMessage, string strLineNo)
 {
 bool boolErrLog = true;

 string strbaseDir = AppDomain.CurrentDomain.BaseDirectory;
 string strErrHeader = "<TR bgColor=\"#E6D4A7\"><TD align=center><font size=\"4\">DataBase</font></TD><TD align=center><font size=\"4\">User</font></TD><TD align=center><font size=\"4\">Date</font></TD><TD align=center><font size=\"4\">DLL Name</font></TD><TD align=center><font size=\"4\">Error In<font></TD><TD align=center><font size=\"4\">File Name</font></TD><TD align=center><font size=\"4\">File Location</font></TD><TD align=center><font size=\"4\">Error Method Name</font></TD><TD align=center><font size=\"4\">Error Message</font></TD><TD align=center><font size=\"4\">Error Line No</font></TD></TR>";
 string strTitle = "<h2 align=center>" + "My Website Error Log Information" + "</h2>";
 string strErrorTime = DateTime.Now.Month.ToString() + "-" + DateTime.Now.Day.ToString() + "-" + DateTime.Now.Year.ToString();
 string strDBName = "-", strLoginUser = "-";
 string strLogFilePath = strbaseDir + "Logs\\" + "ErrorLog" + "_" + strErrorTime + ".html";

 if (!Directory.Exists(strbaseDir + "Logs\\"))
 {
 Directory.CreateDirectory(strbaseDir + "Logs\\");
 }

 if (File.Exists(strLogFilePath))
 {
 boolErrLog = false;
 }

 StreamWriter sw = new StreamWriter(strLogFilePath, true);

 if (boolErrLog)
 {
 sw.WriteLine(strTitle + "<TABLE rules=\"all\">");
 sw.WriteLine(strErrHeader);
 } 

 if (HttpContext.Current.Session != null)
 {
 if (HttpContext.Current.Session["DATABASE"] != null)
 strDBName = HttpContext.Current.Session["DATABASE"].ToString();
 if (HttpContext.Current.Session["LoginUser"] != null)
 strLoginUser = HttpContext.Current.Session["LoginUser"].ToString();
 }
 strLogFormat = "<TR><TD>" + strDBName + "</TD><TD>" + strLoginUser + "</TD><TD>" + DateTime.Now.ToString() + "</TD><TD>" + strDLLName + "</TD><TD>" + strErrorIn + "</TD><TD>" + strFileName + "</TD><TD align=center>" + strFileLocation + "</TD><TD>" + strErrMethodName + "</TD><TD>" + strErrMessage + "</TD><TD>" + strLineNo + "</TD></TR>";

 sw.WriteLine(strLogFormat);
 sw.Close();
 }

Step 6: How to call this method in our website

in codebehind events, (ex. button click)
try
 {
 throw new Exception("dotnetpgm Exception");
 }
 catch (Exception ex)
 {
 General objGeneral = new General();
 objGeneral.GetErrorDetails(ex);
 Response.Redirect("ErrorPage.aspx");
 }

Step 7: for catching the Application errors add the code in Global.asax

you can create Global.asax by add new item in the website
protected void Application_Error(object sender, EventArgs e)
 {
 General objGeneral = new General();
 Exception objErr = Server.GetLastError().GetBaseException();
 objGeneral.GetErrorDetails(objErr);
 }


Download the project with full source code.

Build and run the application to log the 'dotnetpgm' exception in the error log file.
you will see it will redirect to ErrorPage.aspx page. But when you get an Application error It just log the error in background.

In this blog, we saw about how to add the simple error logging method in our website. Error Logging will be very useful to detect errors and helps our website to fix the issues.

4 comments:

  1. Hey superb post. Really helpful for new developers like me :)

    ReplyDelete
  2. Thanks Ashwin. Keep reading www.dotnetpgm.blogspot.com

    ReplyDelete
  3. I have read your blog its very attractive and impressive. I like it your blog.

    Dot Net Training in Chennai Dot Net Training in Chennai .Net Online Training .Net Online Training Dot Net Training in Chennai Dot Net Training in Chennai


    Dot Net Online Training Dot Net Online Training LINQ Online Training LINQ Online Training ASP.NET Online Training ASP.NET Online Training

    ReplyDelete

Followers