C# Logger when Handling Exceptions

Having the Logger configured as in the previous post, it is very easy to use it to log exceptions directly. The ILogger interface provides a method called AppendException() which takes a reference of an Exception object, which will log the stack trace, the message and the targetted site of the exception that was thrown. If you are familiar with my previous post, you can use this class from the CsharpGears framework to log your exceptions out-of-the-box. For instance, in ASP.NET web applications, you could use this logger to trace all the exceptions in the global.asax file when handling the event OnApplicationError or anytime an exception occurs and then redirect the user to a custom error page.

Here is the minimum amount of code to set all that up:

/* Set up configuration for the logger */
            string DbProvider = "System.Data.SqlClient";
            string ConnectionString = "...";

            /* Create the logger */
            ILogger Logger = new DbLogger(DbProvider,ConnectionString);
            Configuration.LogLevel = LogLevel.ERROR;

            try
            {
                /* Generate an exception */
                int generates_exception = 1 / 0;
            }
            catch (Exception ex)
            {
                Logger.AppendException(ex);
            }
            /* Retrieve the messages from today */
            List<LogMessage> TodaysLogContent = Logger.ReadLogByDate(DateTime.Now);

            /* Print the log messages from today */
            foreach (LogMessage message in TodaysLogContent)
            {
                Console.WriteLine(message.Message + " " + message.UserName + " " + message.Date + "\n");
            }

Logging Exceptions in ASP.NET websites

protected void Application_Error(object sender, EventArgs e)
            {
                Exception ex = Server.GetLastError();
                string DbProvider = "System.Data.SqlClient";
                string ConnectionString = "...";

                /* Create the logger */
                ILogger Logger = new DbLogger(DbProvider, ConnectionString);
                Configuration.LogLevel = LogLevel.ERROR;
                Logger.AppendException(ex);
                // Clear the error and maybe redirect to some other page...
                Server.ClearError();
            }

You can see that all you need is a few lines of C# code and an object-oriented approach to your log messages is ready to be used. I really find it useful, would appreciate to tell me what do you think about it.

No comments:

Post a Comment