Support us .Net Basics C# SQL ASP.NET ADO.NET MVC Slides C# Programs Subscribe Buy DVD

Logging exception to database - Part 75

Suggested Videos
Part 72 - Windows event viewer
Part 73 - Logging exceptions to the windows eventviewer
Part 74 - Logging exceptions as information entry type in windows eventviewer

In this video we will discuss about loggin exceptions to a database table. The first step is to create the required table, to log the exceptions.

Script to create table - tblLog
Create table tblLog
[Id] int primary key identity(1,1),
[Date] DateTime,
[ExceptionMessage] nvarchar(max)

Stored procedure to log the exception
create procedure spInsertLog
@ExceptionMessage nvarchar(max)
insert into tblLog([Date], [ExceptionMessage])
values (Getdate(), @ExceptionMessage)

Database connection string in web.config. Change it accordingly, to connect to your sql server.
  <add name="DBConnectionString"
  connectionString="data source=.; database=Sample; Integrated Security=SSPI"
  providerName="System.Data.SqlClient" />

Add a class file with name - Logger.cs.
public class Logger
    public static void Log(Exception exception)
        StringBuilder sbExceptionMessage = new StringBuilder();

            sbExceptionMessage.Append("Exception Type" + Environment.NewLine);
            sbExceptionMessage.Append(Environment.NewLine + Environment.NewLine);
            sbExceptionMessage.Append(exception.Message + Environment NewLine + Environment.NewLine);
            sbExceptionMessage.Append("Stack Trace"Environment.NewLine);
            sbExceptionMessage.Append(exception.StackTrace + Environment NewLine + Environment.NewLine);

            exception = exception.InnerException;
        while (exception != null);

    private static void LogToDB(string log)
        // ConfigurationManager class is in System.Configuration namespace
        string connectionString = ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString;
        // SqlConnection is in System.Data.SqlClient namespace
        using (SqlConnection con = new SqlConnection(connectionString))
            SqlCommand cmd = new SqlCommand("spInsertLog", con);
            // CommandType is in System.Data namespace
            cmd.CommandType = CommandType.StoredProcedure;

            SqlParameter parameter = new SqlParameter("@ExceptionMessage", log);


Add a webform with name - Errors.aspx.
<div style="font-family: Arial">
    <table style="border:1px solid black">
            <td style="color:Red">
                <h2>Application Error</h2>
                    An unkown error has occured. We are aware of it and the IT team is currently working
                    on this issue. Sorry for the inconvinience caused.</h3>
                    If you need further assistance, please contact our helpdesk at

Add a webform to the project. Drag and drop a gridview control. Copy and paste the following code in the code behind file, in the Page_Load() event.
    // DataSet is in System.Data namespace
    DataSet ds = new DataSet();
    // This line will throw an exception, as Data.xml 
    // file is not present in the project
    GridView1.DataSource = ds;
//catch (Exception ex)
//    Logger.Log(ex);
//    Server.Transfer("~/Errors.aspx");

Global.asax code:
void Application_Error(object sender, EventArgs e)
    if (Server.GetLastError() != null)
        // Log the exception
        // Clear the exception
        // Transfer the user to Errors.aspx page

Run the application. The exception should be logged to the Database table - tblLog and the user will be redirected to Errors.aspx page.


  1. Hi venkat,

    The above code works fine without adding entries in the Global.asax file.

    Can you plz tell me what is the role of global.asax file here.

    1. pls watch the previous tutorials of this series you find the file is used to handle the exceptions at the application level.when we miss to handle the exceptions at page level.


If you like this website, please share with your friends on facebook and Google+ and recommend us on google using the g+1 button on the top right hand corner.