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:
<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:
<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.
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);
foreach (PropertyInfo pInfo in currentException.GetType().GetProperties())
{
if (((pInfo.Name != "StackTrace") && (pInfo.Name != "InnerException")))
{
if ((pInfo.GetValue(currentException, null) == null))
{
sbExceptionMessageTemplate.AppendFormat("{0}{1}: NULL/Undefined",
Environment.NewLine, pInfo.Name);
}
else
{
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));
}
}
}
}
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);
}
currentException = currentException.InnerException;
intExceptionCount++;
}
The returned StringBuilder is sent to create a TraceListener object (any one of FileTraceListener, EmailTraceListener, or EventLogTraceListener).
FlatFileTraceListener
private static FlatFileTraceListener GetFileTraceListener(TextFormatter formatter)
{
new FlatFileTraceListener(FlatfileName,"----------",
"----------", formatter);
EmailTraceListener
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
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)
{
return new LogWriter(new ILogFilter[0], GetTraceSource(AddToLogSource(logListener)),
nonExistantLogSource, nonExistantLogSource, AddToLogSource(logListener), ErrorCategory, false, true);
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:
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.