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

Customizing asp.net exception Logging - Part 76

Suggested Videos
Part 73 - Logging exceptions to the windows eventviewer
Part 74 - Logging exceptions as information entry type in windows eventviewer
Part 75 - Logging exceptions to database

In this video we will discuss about logging exception to both
1. A database table
2. Windows eventviewer

The ability to log exceptions must be configurable in web.config



Add a key to web.config file using appsettings element. This key determines, where the exceptions are logged.
<appSettings>
  <!--LogProvider = Database|EventViewer|Both-->
  <add key="LogProvider" value="Both"/>
</appSettings>

The "Logger" class reads the "LogProvider" key from web.config and logs the exceptions accordingly.



public class Logger
{
    public static void Log(Exception exception)
    {
        StringBuilder sbExceptionMessage = new StringBuilder();

        do
        {
            sbExceptionMessage.Append("Exception Type" + Environment.NewLine);
            sbExceptionMessage.Append(exception.GetType().Name);
            sbExceptionMessage.Append(Environment.NewLine + Environment.NewLine);
            sbExceptionMessage.Append("Message"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);

        string logProvider = ConfigurationManager.AppSettings["LogProvider"];
        if (logProvider.ToLower() == "both")
        {
            LogToDB(sbExceptionMessage.ToString());
            LogToEventViewer(sbExceptionMessage.ToString());
        }
        else if (logProvider.ToLower() == "database")
        {
            LogToDB(sbExceptionMessage.ToString());
        }
        else if (logProvider.ToLower() == "eventviewer")
        {
            LogToEventViewer(sbExceptionMessage.ToString());
        }
    }

    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);
            cmd.Parameters.Add(parameter);

            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
        }
    }

    private static void LogToEventViewer(string log)
    {
        if (EventLog.SourceExists("PragimTech.com"))
        {
            // Create an instance of the eventlog
            EventLog eventLog = new EventLog("PragimTech");
            // set the source for the eventlog
            eventLog.Source = "PragimTech.com";
            // Write the exception details to the event log as an error
            eventLog.WriteEntry(log, EventLogEntryType.Error);
        }
    }
}

Global.asax, Errors.aspx and WebForm1.aspx HTML and code have not changed from Part 75 - Logging exception to database.

2 comments:

  1. Hallo Vanket,

    thank you for this ecellent video series!

    Only a note for the users to this part:
    On this page http://csharp-video-tutorials.blogspot.de there is the correct code that will work for the case "both".
    if (logProvider.ToLower() == "both")
    {
    LogToDB(sbExceptionMessage.ToString());
    LogToEventViewer(sbExceptionMessage.ToString());
    }
    else if ....

    Don't use the code from the video shown in "else if" at time 10:04.

    Kind regards from Germany...






    ReplyDelete
  2. How to write Log in text file please help me

    ReplyDelete

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.