void Application_Error(object sender, EventArgs e)
{
Exception exc = Server.GetLastError();
if (exc is HttpUnhandledException)
{
if (ConfigurationManager.AppSettings["logErrorsInDb"] == "true")
{
try
{
string UserId = "n/a";
if (Session["usernameEmail"] != null)
{
UserId = Session["usernameEmail"].ToString();
}
string Webpage = Request.PhysicalPath;
// get IP **********************************
string IP = "n/a";
System.Web.HttpContext context = System.Web.HttpContext.Current;
string ipAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (!string.IsNullOrEmpty(ipAddress))
{
string[] addresses = ipAddress.Split(',');
if (addresses.Length != 0)
{
IP = addresses[0];
}
}
else
{
IP = context.Request.ServerVariables["REMOTE_ADDR"];
}
// *******************************************
Persist persist = new Persist();
persist.logError(exc.InnerException.Message, UserId, exc.InnerException.StackTrace, Webpage, IP);
}
catch (Exception ex)
{
}
}
// Pass the error on to the error page.
Server.Transfer("Oops.aspx?handler=Application_Error%20-%20Global.asax", true);
}
My simple error logger:
public void logError(String Message, String UserId, String StackTrace, String Webpage, String IP)
{
using (SqlConnection cn = new SqlConnection(DBConnection.getDBConnection()))
{
int rowsAffected = 0;
String sql = @"INSERT INTO [dbo].[ErrorLog](Message,UserId,StackTrace,Webpage,IP)
VALUES(@Message,@UserId,@StackTrace,@Webpage,@IP)";
SqlCommand cmd = new SqlCommand(sql, cn);
cmd.CommandType = System.Data.CommandType.Text;
if (Message.Length > 1000)
{
Message = Message.Substring(0, 999);
}
cmd.Parameters.AddWithValue("@Message", Message);
cmd.Parameters.AddWithValue("@UserId", UserId);
if (StackTrace.Length > 3000)
{
StackTrace = StackTrace.Substring(0, 2999);
}
cmd.Parameters.AddWithValue("@StackTrace", StackTrace);
if (Webpage.Length > 500)
{
Webpage = Webpage.Substring(0, 499);
}
cmd.Parameters.AddWithValue("@Webpage", Webpage);
cmd.Parameters.AddWithValue("@IP", IP);
try
{
cn.Open();
rowsAffected = cmd.ExecuteNonQuery();
}
catch (Exception err)
{
}
}
}
DDL for table:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ErrorLog](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Message] [nvarchar](1000) NULL,
[Timestamp] [datetime] NULL DEFAULT (getdate()),
[UserId] [nvarchar](50) NULL,
[StackTrace] [nvarchar](max) NULL,
[Webpage] [nvarchar](500) NULL,
[IP] [nvarchar](50) 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, FILLFACTOR = 90) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
No comments:
Post a Comment