Blogs

Blogs

Error Logging Helper

9th September 2014

As a developer it is not uncommon that at some point in time your code is going to crash out and you will be hit with the classic .Net error page. It is important that we as developers can log the error message so we can fix the issue(s) we have.

Below is an example of a Helper library class we use at PSP to log error messages in the Event Viewer.

The code below has four options:

  • LogSuccessAudit – This will log any success message into the event view logs, for example you have a timer job running and you want to log it has started and finished.
  • LogErrorMessage – This will log the error from the try catch statement into the event view.
  • LogErrorMessage with additional parameter to pass through some custom text – This will log the error message from the try catch and will also allow you to pass through some additional information if required to help.
  • GetExceptionLogText – This will return the exception message as text if you wanted to display it.
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Linq;
using System.Text;

    /// <summary>
    /// Error Helper utility class
    /// </summary>
    public static class ErrorHelper
    {
        /// <summary>
        /// Logs the success audit.
        /// </summary>
        /// <param name="informationMessage">The information message.</param>
        public static void LogSuccessAudit(string informationMessage)
        {
            using (EventLog eventLog = new EventLog())
            {
                eventLog.Source = ConfigurationManager.AppSettings["EventViewerSource"];
                eventLog.Log = ConfigurationManager.AppSettings["EventViewerName"];

                var error = new StringBuilder();
                error.Append(informationMessage);

                if (!EventLog.SourceExists(eventLog.Source))
                {
                    EventLog.CreateEventSource(eventLog.Source, eventLog.Log);
                }

                eventLog.WriteEntry(error.ToString(), EventLogEntryType.SuccessAudit);
                eventLog.Close();
            }
        }

        /// <summary>
        /// Logs the error message.
        /// </summary>
        /// <param name="exception">The exception.</param>
        public static void LogErrorMessage(Exception exception)
        {
            if (exception.Message != "Thread was being aborted.")
            {
                using (EventLog eventLog = new EventLog())
                {
                    eventLog.Source = ConfigurationManager.AppSettings["EventViewerSource"];
                    eventLog.Log = ConfigurationManager.AppSettings["EventViewerName"];

                    var error = new StringBuilder();
                    error.Append(GetExceptionLogText(exception));

                    if (!EventLog.SourceExists(eventLog.Source))
                    {
                        EventLog.CreateEventSource(eventLog.Source, eventLog.Log);
                    }

                    eventLog.WriteEntry(error.ToString(), EventLogEntryType.Error);
                    eventLog.Close();
                }
            }
        }

        /// <summary>
        /// Logs the error message.
        /// </summary>
        /// <param name="exception">The exception.</param>
        /// <param name="message">The message.</param>
        public static void LogErrorMessage(Exception exception, string message)
        {
            if (exception.Message != "Thread was being aborted.")
            {
                using (EventLog eventLog = new EventLog())
                {
                    eventLog.Source = ConfigurationManager.AppSettings["EventViewerSource"];
                    eventLog.Log = ConfigurationManager.AppSettings["EventViewerName"];

                    var error = new StringBuilder();
                    error.Append(GetExceptionLogText(exception));
                    error.Append(" message: ");
                    error.Append(message);

                    if (!EventLog.SourceExists(eventLog.Source))
                    {
                        EventLog.CreateEventSource(eventLog.Source, eventLog.Log);
                    }

                    eventLog.WriteEntry(error.ToString(), EventLogEntryType.Error);
                    eventLog.Close();
                }
            }
        }

        /// <summary>
        /// Returns the contents of an exception for display in a log message
        /// </summary>
        /// <param name="ex">The exception to log</param>
        /// <returns>A string built up from the exception contents</returns>
        public static string GetExceptionLogText(Exception ex)
        {
            int errorDepth = 0;
            StringBuilder error = new StringBuilder();
            while (ex != null && errorDepth <= 10)
            {
                error.AppendFormat(ex.ToString());
                ex = ex.InnerException;
                if (ex != null && ++errorDepth <= 10)
                {
                    error.AppendFormat("+++Inner Excepton {0}+++\n", errorDepth);
                }
            }

            return error.ToString();
        }
    }
This website uses cookies to provide the best possible experience. By continuing to use our website you are agreeing to our use of cookies.