How to save Error log in Asp.net

Ranjeet_8
Posted by Ranjeet_8 under ASP.NET category on | Points: 40 | Views : 2798
Create Global.asax Page
and Try this code.

<%@ Import Namespace="System.Data"%>
<%@ Import Namespace="System.Data.SqlClient" %>


  void Application_Error(object sender, EventArgs e)
{
Try
{
// Code that runs when an unhandled error occurs

// Get the error details
HttpContext CurrentHTTPcontext = HttpContext.Current;
HttpException lastErrorWrapper = Server.GetLastError() as HttpException;

Exception lastError = lastErrorWrapper;
if (lastErrorWrapper.InnerException != null)
lastError = lastErrorWrapper.InnerException;

string ErrorPageURL = CurrentHTTPcontext.Request.Url.ToString();
string ErrorMessage = lastError.Message;
string ErrorStackTrace = lastError.StackTrace;

MainFunction mainfun = new MainFunction();
SqlConnection sqlcon = new SqlConnection(ConfigurationSettings.AppSettings["CON"]);
Try
{
SqlCommand sqlcmd = new SqlCommand();
sqlcmd.CommandType = CommandType.StoredProcedure;
sqlcmd.Connection = sqlcon;
sqlcmd.Parameters.Add(new SqlParameter("@PageURL", SqlDbType.VarChar, 500)).Value = Server.HtmlEncode(ErrorPageURL);
sqlcmd.Parameters.Add(new SqlParameter("@ErrorMessage", SqlDbType.VarChar, 2000)).Value = Server.HtmlEncode(ErrorMessage);
sqlcmd.Parameters.Add(new SqlParameter("@ErrorStackTrace", SqlDbType.Text)).Value = Server.HtmlEncode(ErrorStackTrace);
sqlcmd.CommandText = "Sp__ErrorLog"; // Procedure Name

if (sqlcon.State == ConnectionState.Closed)
{
sqlcon.Open();
}
sqlcmd.ExecuteNonQuery();
if (sqlcon.State == ConnectionState.Open)
{
sqlcon.Close();
}
}
catch
{
if (sqlcon.State == ConnectionState.Open)
{
sqlcon.Close();
}
}
}
catch {
}

}


Create Table:
CREATE TABLE [dbo].[ErrorLog](
[AutoID] [numeric](18, 0) IDENTITY(1,1) NOT NULL,
[PageURL] [varchar](500) NULL,
[ErrorMessage] [varchar](2000) NULL,
[ErrorStackTrace] [text] NULL,
[CreatedDateTime] [datetime] NULL
)


Create Procedure:
CREATE Procedure [dbo].[Sp_ErrorLog]
(
@PageURL varchar(500),
@ErrorMessage varchar(2000),
@ErrorStackTrace text
)
AS
Begin

insert into ErrorLog
([PageURL],[ErrorMessage],[ErrorStackTrace],[CreatedDateTime])
Values(@PageURL,@ErrorMessage,@ErrorStackTrace,GETDATE())

End

Comments or Responses

Posted by: Nagasundar_Tn on: 7/24/2012 Level:Starter | Status: [Member] | Points: 10
Thanks for your reply
Posted by: Irulswift on: 5/10/2013 Level:Starter | Status: [Member] | Points: 10
Thank's for sharing code



Login to post response