Logging Exception to Database


Monitoring the errors of a live application is very important to avoid any inconvenience. In C# to handle exceptions the try, catch and finally keywords are used, so in this article, we will learn how to catch the error and log error details to the Database table so developers can fix it as soon as possible.
So let us start by creating the application.
Use the following procedure to create a web site:
  1. "Start" - "All Programs" - "Microsoft Visual Studio 2010".
  2. "File" - "New" - "Web Site..." then select "C#" - "Empty Weh Site" (to avoid adding a master page).
  3. Provide the project a name such as "ExceptionLoggingToDatabase" 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 as follows.
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>  
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  3. <html xmlns="http://www.w3.org/1999/xhtml">  
  4. <head runat="server">  
  5. <title></title>  
  6. </head>  
  7. <body bgcolor="silver">  
  8. <form id="form1" runat="server">  
  9. <asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None">  
  10. </asp:GridView>  
  11. </form>  
  12. </body>  
  13. </html>
In the preceding source code, we have taken the one grid view and we try to assign a file as the data source for the grid view that is not available so it can generate the error file not found and we can log these error details to the database table.
Now create the table and provide a name as Tbl_ExceptionLoggingToDataBase or as you wish to store the exception details as:
  1. USE [C#corner]  
  2. GO  
  4. /****** Object:  Table [dbo].[Tbl_ExceptionLoggingToDataBase]    Script Date: 15-04-2014 23:34:43 ******/  
  6. GO  
  9. GO  
  12. GO  
  14. CREATE TABLE [dbo].[Tbl_ExceptionLoggingToDataBase](  
  15.     [Logid] [bigint] IDENTITY(1,1) NOT NULL,  
  16.     [ExceptionMsg] [varchar](100) NULL,  
  17.     [ExceptionType] [varchar](100) NULL,  
  18.     [ExceptionSource] [nvarchar](maxNULL,  
  19.     [ExceptionURL] [varchar](100) NULL,  
  20.     [Logdate] [datetime] NULL,  
  21.  CONSTRAINT [PK_Tbl_ExceptionLoggingToDataBase] PRIMARY KEY CLUSTERED   
  22. (  
  23.     [Logid] ASC  
  27. GO  
  30. GO 
The table will look as:
 Now create the Stored Procedure to log the exception into the database table as:
  1. Create Procedure ExceptionLoggingToDataBase  
  2. (  
  3. @ExceptionMsg varchar(100)=null,  
  4. @ExceptionType varchar(100)=null,  
  5. @ExceptionSource nvarchar(max)=null,  
  6. @ExceptionURL varchar(100)=null  
  7. )  
  8. as  
  9. begin  
  10. Insert into Tbl_ExceptionLoggingToDataBase  
  11. (  
  12. ExceptionMsg ,  
  13. ExceptionType,   
  14. ExceptionSource,  
  15. ExceptionURL,  
  16. Logdate  
  17. )  
  18. select  
  19. @ExceptionMsg,  
  20. @ExceptionType,  
  21. @ExceptionSource,  
  22. @ExceptionURL,  
  23. getdate()  
  24. End 
Now create the class named ExceptionLogging to log the error to the database table and write the following code as:
  1. using System;  
  2. using context = System.Web.HttpContext;  
  3. using System.Configuration;  
  4. using System.Data.SqlClient;  
  5. using System.Data;  
  7. /// <summary>  
  8. /// Summary description for ExceptionLogging  
  9. /// article by Vithal Wadje  
  11. /// </summary>  
  12. public static class ExceptionLogging  
  13. {  
  15.     private static String exepurl;  
  16.     static SqlConnection con;  
  17.     private static void connecttion()  
  18.     {  
  19.         string constr = ConfigurationManager.ConnectionStrings["CharpCorner"].ToString();  
  20.         con = new SqlConnection(constr);  
  21.         con.Open();  
  22.     }  
  23.     public static void SendExcepToDB(Exception exdb)  
  24.     {
  25.         connecttion();  
  26.         exepurl = context.Current.Request.Url.ToString();  
  27.         SqlCommand com = new SqlCommand("ExceptionLoggingToDataBase", con);  
  28.         com.CommandType = CommandType.StoredProcedure;  
  29.         com.Parameters.AddWithValue("@ExceptionMsg", exdb.Message.ToString());  
  30.         com.Parameters.AddWithValue("@ExceptionType", exdb.GetType().Name.ToString());  
  31.         com.Parameters.AddWithValue("@ExceptionURL", exepurl);  
  32.         com.Parameters.AddWithValue("@ExceptionSource", exdb.StackTrace.ToString());  
  33.         com.ExecuteNonQuery();
  34.     }

In the code above we have created a SendExcepToDB method that accepts the Exception class reference object and we can call this method from the default.aspx.cs file.

Now open the default.aspx.cs page and write the following code to assign the data source to the grid view:
  1. protected void Page_Load(object sender, EventArgs e)      
  2. {      
  3.     try      
  4.     {  
  5.         DataSet ds = new DataSet();      
  6.         ds.ReadXml(Server.MapPath("~/emp.xml"));      
  7.         GridView1.DataSource = ds;      
  8.         GridView1.DataBind();  
  9.     }      
  10.     catch (Exception ex)      
  11.     {  
  12.     ExceptionLogging.SendExcepToDB(ex);      
  13.     Label1.Text = "Some Technical Error occurred,Please visit after some time";  
  14.     }   
  15. } 
In the code above, we have used try and catch keywords to handle the exception, from the first in the try block we are trying to assign the emp.xml as the data source to the grid view that is not available and in the catch block we are calling the method SendExcepToDB of the class ExceptionLogging to log the error by ing the Exception class reference object.
Now run the application The following dummy message we will be shown to the user and the actual error will be logged to the database table as:
Now all the Exception details will be logged into the database table as:

We can see that in the preceding table all the Exception details are logged into the database with an application URL and page Name along with other details that helps developers to fix the error easily.
  • Download the Zip file from the attachment for the full source code of the application.
  • Make the changes in the web.config file depending on your server location.

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