Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

A Simple Way of Logging Exception Information

2.73/5 (8 votes)
8 May 2007CPOL2 min read 1   311  
Provides a simple way to log information using Logging Application Blocks of the Enterprise Library.

Introduction

This is a simple sample application to use the Logging Application Block of Enterprise Library to log exception messages to the appropriate Listener. It provides the option of choosing logging listeners. According to the level of the exception, you can choose the Listener type. In the case of an application's unexpected shutdown, you can set the Listener type as email and event viewer.

When an exception is thrown, catch it and send to this class.

What it does?
  • Serialize the exception tree into text.
  • This text is used as the text formatter for all Listener types.
  • According to the selected Listener type, it will call the Listeners.
  • The Listener takes the formatter as input and returns the appropriate TraceListener object.
  • Bind the TraceListener object to a list of TraceListeners.
  • Pass this list of listeners to the LogWriter object.
  • In turn, the LogSource object is created with this list of listeners.
  • Send this LogWriter object to LogEntry to log the exception information.

How to Use?

  • Add the SimpleLogger file to your application.
  • Call the method PublishException of SimpleLogger in the catch block of the method.
  • Pass the exception object and ListenerType as parameter.

Using the code

In the web.config file, add the configsection for the logging library:

XML
<configSections>
    <section name="loggingConfiguration" 
      type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, 
            Microsoft.Practices.EnterpriseLibrary.Logging,Version=2.0.0.0, 
            Culture=neutral,PublicKeyToken=null"/>
</configSections>

In appsettings, provide the flat file path for the logging information in the flat file:

XML
<appSettings>
    <add key="logFilename" value=".\ErrorLog\Log\"/>
</appSettings>

SerializeToText method

Here, loop through the exception object properties and get the stack trace, InnerException information and etc., and bind to the StringBuilder to create the TextFormatter.

C#
while (!(currentException == null))
{
    sbExceptionMessageTemplate.AppendFormat(
      "{0}{0}Exception Information: Exception #{1}{0}{2}", 
      Environment.NewLine, intExceptionCount.ToString(), TEXT_SEPERATOR);
    sbExceptionMessageTemplate.AppendFormat(
      "{0}Exception Type: {1}", Environment.NewLine, 
      currentException.GetType().FullName);

    //Getting the properties of the current exception
    foreach (PropertyInfo pInfo in currentException.GetType().GetProperties())
    {
        //StackTrace and Innerexception are treated seperately
        if (((pInfo.Name != "StackTrace") && (pInfo.Name != "InnerException")))
        {
            //Check for NULL property Values
            if ((pInfo.GetValue(currentException, null) == null))
            {
                sbExceptionMessageTemplate.AppendFormat("{0}{1}: NULL/Undefined", 
                                                Environment.NewLine, pInfo.Name);

            }
            else
            {
                //Get the associated Additional Information 
                //if the Exception is of Type ApplicationExceptionBase

                if (pInfo.Name == "AdditionalInformation")
                {
                    if (!(pInfo.GetValue(currentException, null) == null))
                    {
                        customAdditionalInfo = ((Dictionary<string, string>)
                                   (pInfo.GetValue(currentException, null)));
                        if ((customAdditionalInfo.Count > 0))
                        {
                            sbExceptionMessageTemplate.AppendFormat(
                                    "{0}Additional Exception Information:", 
                                    Environment.NewLine);
                            foreach (String lstrParam in customAdditionalInfo.Keys)
                            {
                                sbExceptionMessageTemplate.AppendFormat("{0} {1}: {2}", 
                                     Environment.NewLine, lstrParam, 
                                     customAdditionalInfo[lstrParam]);
                            }
                        }
                    }
                }
                else
                {
                    sbExceptionMessageTemplate.AppendFormat("{0}{1}: {2}", 
                      Environment.NewLine, pInfo.Name, 
                      pInfo.GetValue(currentException, null));
                }
            }
        }
    }

    //Writing out the Stack Trace Information
    if (!(currentException.StackTrace == null))
    {
        sbExceptionMessageTemplate.AppendFormat("{0}{0}Stack Trace Information{0}{1}", 
                                                Environment.NewLine, TEXT_SEPERATOR);
        sbExceptionMessageTemplate.AppendFormat("{0}{1}", Environment.NewLine, 
                                                currentException.StackTrace);
    }

    //Get the Inner Exception
    currentException = currentException.InnerException;
    intExceptionCount++;
}

The returned StringBuilder is sent to create a TraceListener object (any one of FileTraceListener, EmailTraceListener, or EventLogTraceListener).

FlatFileTraceListener

C#
private static FlatFileTraceListener GetFileTraceListener(TextFormatter formatter)
{
    // Log messages to a log file.
    // Use the formatter passed
    new FlatFileTraceListener(FlatfileName,"----------",
        "----------", formatter);

EmailTraceListener

C#
private static EmailTraceListener GetEmailTraceListener(TextFormatter formatter)
{
  mailListener = new EmailTraceListener("Test@xxxxx.com", "Test@xxxxxxx.com", "Admin",
                 "<<ApplicationName>>", "smtp.xxxxxx.com", 25, formatter);
  return mailListener;

EventLogTraceListener

C#
eventlogListener = new FormattedEventLogTraceListener(
      new EventLog(logName, Environment.MachineName, SourceName), formatter);

The collection of trace listeners are sent to the LogWriter:

C#
private static LogWriter GetLogWriter(List<TraceListener> logListener)
{
    // Let's glue it all together.
    // I won't log a couple of the Special
    // Sources: All Events and Events not
    // using "Error" or "Debug" categories.
    return new LogWriter(new ILogFilter[0], // ICollection<ILogFilter> filters
       // IDictionary<string, LogSource> traceSources
       GetTraceSource(AddToLogSource(logListener)),
       nonExistantLogSource, // LogSource allEventsTraceSource
       nonExistantLogSource, // LogSource notProcessedTraceSource
       AddToLogSource(logListener), // LogSource errorsTraceSource
       ErrorCategory, // string defaultCategory
       false, // bool tracingEnabled
       true); // bool logWarningsWhenNoCategoriesMatch

PublishException

this is the method which exposed out to log the information

public static void PublishException(Exception ex, string category, ListenerType ltype)
{
    Dictionary<string, string> additionalInfo = new Dictionary<string, string>();

    /// Writes a message to the log using the specified
    /// category.
    _writer = GetLogWriter(logFileListener);

    _writer.Write(entry);

Call this PublishException method in your catch block:

C#
catch(Exception ex)
{
    SimpleLogger.PublishException(ex, ListenerType.EventViewer);
    SimpleLogger.PublishException(ex, ListenerType.File); 
    SimpleLogger.PublishException(ex,ListenerType.Email); 
}

Conclusion

This is very simple way of logging your exception information.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)