Exception Logging to Text file

Background
Monitoring the error of live application is very important to avoid any inconvenience,In C# to handle exception try ,catch ,finally keyword are used,so in this article we will learn how to catch the error and log error details to text file so developer can fix it as soon as possible.
so let us start by creating the application.
 
Create Web Site as
  1. "Start" - "All Programs" - "Microsoft Visual Studio 2010".
  2. "File" - "New" - "Project..." then select "C#" - "Empty Project" (to avoid adding a master page).
  3. Provide the project a name such as "ExceptionLoggingToTextFile" or another as you wish and specify the location.
  4. Then right-click on Solution Explorer rhen select "Add New Item" - "Default.aspx" page.
  5. Drag and Drop one GridView to the Default.aspx page. Then the page will look such as follows.
 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body bgcolor="silver">
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None">
</asp:GridView>
</form>
</body>
</html>
In the above source code ,we have taken the one Grid view and we try to assign file as data source to grid view which is not available so it can generate the error file not found and we can log these error details to the text files.
 
Now create the Class Named ExceptionLogging to log the error to text file and write the following code as
ExceptionLogging.cs
  1. using System;  
  2. using System.IO;  
  3. using context = System.Web.HttpContext;  
  4.   
  5. /// <summary>  
  6. /// Summary description for ExceptionLogging  
  7. /// </summary>  
  8. public static class ExceptionLogging  
  9. {  
  10.   
  11.  private  static String ErrorlineNo, Errormsg, extype, exurl, hostIp,ErrorLocation, HostAdd;  
  12.                             
  13.     public static void SendErrorToText(Exception ex)  
  14.     {  
  15.         var line = Environment.NewLine + Environment.NewLine;  
  16.   
  17.         ErrorlineNo = ex.StackTrace.Substring(ex.StackTrace.Length - 7, 7);  
  18.         Errormsg = ex.GetType().Name.ToString();  
  19.         extype = ex.GetType().ToString();  
  20.         exurl = context.Current.Request.Url.ToString();  
  21.         ErrorLocation = ex.Message.ToString();  
  22.   
  23.         try  
  24.         {  
  25.             string filepath = context.Current.Server.MapPath("~/ExceptionDetailsFile/");  //Text File Path
  26.   
  27.             if (!Directory.Exists(filepath))  
  28.             {  
  29.                 Directory.CreateDirectory(filepath);  
  30.   
  31.             }  
  32.             filepath = filepath + DateTime.Today.ToString("dd-MM-yy") + ".txt";   //Text File Name
  33.             if (!File.Exists(filepath))  
  34.             {  
  35.   
  36.   
  37.                 File.Create(filepath).Dispose();  
  38.   
  39.             }  
  40.             using (StreamWriter sw = File.AppendText(filepath))  
  41.             {  
  42.                 string error = "Log Written Date:" + " " + DateTime.Now.ToString() + line + "Error Line No :" + " " + ErrorlineNo + line + "Error Message:" + " " + Errormsg + line + "Exception Type:" + " " + extype + line + "Error Location :" + " " + ErrorLocation + line + " Error Page Url:" + " " + exurl + line + "User Host IP:" + " " + hostIp + line;  
  43.                 sw.WriteLine("-----------Exception Details on " + " " + DateTime.Now.ToString() + "-----------------");  
  44.                 sw.WriteLine("-------------------------------------------------------------------------------------");  
  45.                 sw.WriteLine(line);  
  46.                 sw.WriteLine(error);  
  47.                 sw.WriteLine("--------------------------------*End*------------------------------------------");  
  48.                 sw.WriteLine(line);  
  49.                 sw.Flush();  
  50.                 sw.Close();  
  51.   
  52.             }  
  53.   
  54.         }  
  55.         catch (Exception e)  
  56.         {  
  57.             e.ToString();  
  58.   
  59.         }  
  60.     }  
  61.   

 In the above code we have created SendErrorToText method which accept the Exception class reference object  and we can call this method from default.aspx.cs class page
Now open the default.aspx.cs page and write the following code  to assign the data source to grid view
  1. protected void Page_Load(object sender, EventArgs e)  
  2.    {  
  3.        try  
  4.        {  
  5.   
  6.            DataSet ds = new DataSet();  
  7.            ds.ReadXml(Server.MapPath("~/emp.xml"));  
  8.            GridView1.DataSource = ds;  
  9.            GridView1.DataBind();  
  10.   
  11.        }  
  12.        catch (Exception ex)  
  13.        {  
  14.   
  15.        ExceptionLogging.SendErrorToText(ex);  
  16.        Label1.Text = "Some Technical Error occurred,Please visit after some time";
     
  17.        }  
  18.      
  19.    } 
 In the above code ,we have used Try,catch  keyword to handle the exception ,from first in try block we are trying to assign the emp.xml as data source to grid view  which is not available and in catch block we calling the method SendErrorToText of class ExceptionLogging to log error by ing the Exception class reference object.
Now Run the application The following dummy message we will be shown to user and actual error will be logged to text file as
 
 
 
Now open the text file from your application current path ,in my system the text file is generated at the location E:\Csharpcorner\ExceptionLoggingToTextFile\ExceptionDetailsFile in which actual error details are logged as, 
 
 
 
 In the above we can see that the all the error details are logged correctly.
  Note
  • Download the Zip file from the attachment for the full source code of the application
Summary

I hope this article is useful for all readers, if you have any suggestion then please contact me including beginners also.
 
 

Up Next
    Ebook Download
    View all
    Learn
    View all