Exception Logging Using The Database

This is a simple technique I use to log exceptions in all my web applications.

First lets start by adding the following to the web.config:

<appSettings>
<add key="LogUnhandledExceptions" value="true"/>
</appSettings>

Second, we add the following bit inside the Application_Error event of the Global.asax file. This will capture all the unhandled exceptions and log them into the database:

private static bool logUnhandledExceptions = Convert.ToBoolean(ConfigurationManager.AppSettings["LogUnhandledExceptions"]);
.
.
.
void Application_Error(object sender, EventArgs e)
{
    if (logUnhandledExceptions)
    {
        if (Context != null)
        {
            if (Server.GetLastError() != null)
            {
                //Get reference to the source of the exception chain
                Exception ex = Context.Server.GetLastError().GetBaseException();

                YourCompany.Helpers.ExceptionHandler.Log(ex);
            }
        }
    }
}

And now finally the main part. This is the class which will log all the relavent information related to the exception in the DB.

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Diagnostics;
using System.Data.SqlClient;
using System.Web.Configuration;

namespace YourCompany.Helpers
{
    public static class ExceptionHandler
    {
        public static void Log(Exception ex)
        {
            if (ex.GetBaseException() != null)
            {
                try
                {
                    HttpContext context = HttpContext.Current;
                    HttpBrowserCapabilities browser = context.Request.Browser;

                    string referer = String.Empty;

                    if (context.Request.UrlReferrer != null)
                    {
                        referer = context.Request.UrlReferrer.ToString();
                    }

                    using (SqlConnection sqlConnection = new SqlConnection(WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
                    {
                        using (SqlCommand sqlCommand = new SqlCommand())
                        {
                            sqlCommand.Connection = sqlConnection;
                            sqlCommand.CommandType = CommandType.StoredProcedure;
                            sqlCommand.CommandText = "EventLog_Insert";

                            sqlCommand.Parameters.Add("@Source", SqlDbType.NVarChar).Value = ex.Source;
                            sqlCommand.Parameters.Add("@Message", SqlDbType.NVarChar).Value = ex.Message;
                            sqlCommand.Parameters.Add("@Form", SqlDbType.NVarChar).Value = context.Request.Form.ToString();
                            sqlCommand.Parameters.Add("@Path", SqlDbType.NVarChar).Value = context.Request.Path.ToString();
                            sqlCommand.Parameters.Add("@QueryString", SqlDbType.NVarChar).Value = context.Request.QueryString.ToString();
                            sqlCommand.Parameters.Add("@TargetSite", SqlDbType.NVarChar).Value = ex.TargetSite.ToString();
                            sqlCommand.Parameters.Add("@StackTrace", SqlDbType.NVarChar).Value = ex.StackTrace.ToString();
                            sqlCommand.Parameters.Add("@Referer", SqlDbType.NVarChar).Value = referer;
                            sqlCommand.Parameters.Add("@MachineName", SqlDbType.NVarChar).Value = context.Server.MachineName.ToString();
                            sqlCommand.Parameters.Add("@IPAddress", SqlDbType.NVarChar).Value = context.Request.UserHostAddress;
                            sqlCommand.Parameters.Add("@BrowserType", SqlDbType.NVarChar).Value = browser.Type;
                            sqlCommand.Parameters.Add("@BrowserName", SqlDbType.NVarChar).Value = browser.Browser;
                            sqlCommand.Parameters.Add("@BrowserVersion", SqlDbType.NVarChar).Value = browser.Version;
                            sqlCommand.Parameters.Add("@BrowserPlatform", SqlDbType.NVarChar).Value = browser.Platform;
                            sqlCommand.Parameters.Add("@SupportsCookies", SqlDbType.Bit).Value = browser.Cookies;
                            sqlCommand.Parameters.Add("@IsCrawler", SqlDbType.Bit).Value = browser.Crawler;

                            sqlConnection.Open();

                            sqlCommand.ExecuteNonQuery();
                        }
                    }
                }
                catch
                {
                    // database error, not much you can do here except logging the error in the windows event log
                    EventLog.WriteEntry(ex.Source, "Database Error From Exception Handler!", EventLogEntryType.Error);
                }
            }
        }
    }
}
If you liked this post, 🗞 subscribe to my newsletter and follow me on 𝕏!