Click here to Skip to main content
13,250,883 members (47,363 online)
Click here to Skip to main content
Add your own
alternative version


16 bookmarked
Posted 8 May 2007

A Simple Way of Logging Exception Information

, 8 May 2007
Rate this:
Please Sign up or sign in to vote.
Provides a simple way to log information using Logging Application Blocks of the Enterprise Library.


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:

    <section name="loggingConfiguration" 


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

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

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.

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

    //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);

                //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))
                                    "{0}Additional Exception Information:", 
                            foreach (String lstrParam in customAdditionalInfo.Keys)
                                sbExceptionMessageTemplate.AppendFormat("{0} {1}: {2}", 
                                     Environment.NewLine, lstrParam, 
                    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, 

    //Get the Inner Exception
    currentException = currentException.InnerException;

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


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


private static EmailTraceListener GetEmailTraceListener(TextFormatter formatter)
  mailListener = new EmailTraceListener("", "", "Admin",
                 "<<ApplicationName>>", "", 25, formatter);
  return mailListener;


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

The collection of trace listeners are sent to the LogWriter:

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
       nonExistantLogSource, // LogSource allEventsTraceSource
       nonExistantLogSource, // LogSource notProcessedTraceSource
       AddToLogSource(logListener), // LogSource errorsTraceSource
       ErrorCategory, // string defaultCategory
       false, // bool tracingEnabled
       true); // bool logWarningsWhenNoCategoriesMatch


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);


Call this PublishException method in your catch block:

catch(Exception ex)
    SimpleLogger.PublishException(ex, ListenerType.EventViewer);
    SimpleLogger.PublishException(ex, ListenerType.File); 


This is very simple way of logging your exception information.


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


About the Author

Anandhi Swamy
India India
No Biography provided

You may also be interested in...

Comments and Discussions

GeneralImages missing Pin
mav.northwind9-May-07 8:47
membermav.northwind9-May-07 8:47 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.171114.1 | Last Updated 9 May 2007
Article Copyright 2007 by Anandhi Swamy
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid