Asp.Net: Create Error log table in SQL database in ASP.NET application using C#.

Aman Sharma
0
In this article I will explain how to maintain Error log table in SQL server in AS.NET application.

Description:


Implementation:

1.     Create Table in SQL Server i.e. Error_log:

CREATE TABLE [dbo].[Error_log](
[Error_id] [int] IDENTITY(1,1) NOT NULL,
[page_Name] [varchar](200) NULL,
[method_name] [varchar](200) NULL,
[line_No] [int] NULL,
[error_Message] [varchar](max) NULL,
[error_date] [datetime] NULL
)


2.     Now Create Stored procedure to Insert data:

Create proc Sp_Error_Log
@page varchar(200),
@method varchar(200),
@lineno int ,
@error varchar(max)
as begin
Insert into Error_log(page_Name,method_name,line_No,[error_Message])
values (@page,@method,@lineno,@error)
end


3.     Now Create following  method in Class ex. Error.cs:

public static void Create_Error_Log(Exception excep)
    {
        string ErrorMessgage = excep.Message;
        System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(excep, true);
        string pagename = trace.GetFrame((trace.FrameCount - 1)).GetFileName();
        string method = trace.GetFrame((trace.FrameCount - 1)).GetMethod().ToString();
        Int32 lineNumber = trace.GetFrame((trace.FrameCount - 1)).GetFileLineNumber();
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString);
        con.Open();
        SqlCommand cmd = new SqlCommand("Sp_Error_Log", con);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@page", pagename);
        cmd.Parameters.AddWithValue("@method", method);
        cmd.Parameters.AddWithValue("@lineno", lineNumber);
        cmd.Parameters.AddWithValue("@error", ErrorMessgage);
        cmd.ExecuteNonQuery();
        con.Close();
    }


4.     Now Call this method in catch(ex):

try
 {

 }

 catch (Exception ex)
 {
  ErrorLog.Create_Error_Log(ex);
 }

In this application I will write following information to database table:

Page_Name : Page Name where error occurs
Method_name : Method name in which error occurs.

Line_No : Line number of error .
Error_Message: Error message to save in SQL server Table.

This is good practice to maintain error log in database. This will help us to record error list.

Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !