Please refer this code. Add a TextFile name ErroLogs.txt in ErrorLogs folder under the root directory.
Default.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
try
{
int a = 0;
int i = 10 / a;
}
catch (Exception)
{
throw;
}
}
Global.asax
<%@ Application Language="C#" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.IO" %>
void Application_Error(object sender, EventArgs e)
{
string filename = Server.MapPath("~/ErrorLogs/") + "ErroLogs.txt";
StreamWriter sw = new System.IO.StreamWriter(filename, true);
sw.Write(DateTime.Now + "\n\r" + ((System.Exception)(Server.GetLastError().InnerException)).Message.Trim() + "\n\r\n\r");
sw.Close();
/*
Write code here to save the DateTime and Error Message
*/
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
string sqlStatment = "INSERT INTO ErrorLog VALUES(@Date,@Message)";
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(sqlStatment, con))
{
con.Open();
cmd.Parameters.AddWithValue("@Date", DateTime.Now);
cmd.Parameters.AddWithValue("@Message", ((System.Exception)(Server.GetLastError().InnerException)).Message.Trim());
cmd.ExecuteNonQuery();
con.Close();
}
}
Response.Redirect("~/ErrorLogs/Error.aspx?Message=" + ((System.Exception)(Server.GetLastError().InnerException)).Message.Trim());
}
SQL
CREATE TABLE [dbo].[ErrorLog](
[ID] [int] IDENTITY(1,1) NOT NULL,
[ErrorDate] [datetime] NOT NULL,
[Message] [nvarchar](max) NOT NULL,
CONSTRAINT [PK_ErrorLog] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO