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
- "Start" - "All Programs" - "Microsoft Visual Studio 2010".
- "File" - "New" - "Project..." then select "C#" - "Empty Project" (to avoid adding a master page).
- Provide the project a name such as "ExceptionLoggingToTextFile" or another as you wish and specify the location.
- Then right-click on Solution Explorer rhen select "Add New Item" - "Default.aspx" page.
- 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
using System; using System.IO; using context = System.Web.HttpContext; /// <summary> /// Summary description for ExceptionLogging /// </summary> public static class ExceptionLogging { private static String ErrorlineNo, Errormsg, extype, exurl, hostIp,ErrorLocation, HostAdd; public static void SendErrorToText(Exception ex) { var line = Environment.NewLine + Environment.NewLine; ErrorlineNo = ex.StackTrace.Substring(ex.StackTrace.Length - 7, 7); Errormsg = ex.GetType().Name.ToString(); extype = ex.GetType().ToString(); exurl = context.Current.Request.Url.ToString(); ErrorLocation = ex.Message.ToString(); try { string filepath = context.Current.Server.MapPath("~/ExceptionDetailsFile/"); //Text File Path if (!Directory.Exists(filepath)) { Directory.CreateDirectory(filepath); } filepath = filepath + DateTime.Today.ToString("dd-MM-yy") + ".txt"; //Text File Name if (!File.Exists(filepath)) { File.Create(filepath).Dispose(); } using (StreamWriter sw = File.AppendText(filepath)) { 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; sw.WriteLine("-----------Exception Details on " + " " + DateTime.Now.ToString() + "-----------------"); sw.WriteLine("-------------------------------------------------------------------------------------"); sw.WriteLine(line); sw.WriteLine(error); sw.WriteLine("--------------------------------*End*------------------------------------------"); sw.WriteLine(line); sw.Flush(); sw.Close(); } } catch (Exception e) { e.ToString(); } } }
Now open the default.aspx.cs page and write the following code to assign the data source to grid view
protected void Page_Load(object sender, EventArgs e) { try { DataSet ds = new DataSet(); ds.ReadXml(Server.MapPath("~/emp.xml")); GridView1.DataSource = ds; GridView1.DataBind(); } catch (Exception ex) { ExceptionLogging.SendErrorToText(ex); Label1.Text = "Some Technical Error occurred,Please visit after some time"; } }
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.
Download Aspose : API To Create and Convert Files
Download Aspose : API To Create and Convert Files
Summary
I hope this article is useful for all readers, if you have any suggestion then please contact me including beginners also.
Post a Comment