记录异常信息的简单方法






2.73/5 (8投票s)
提供了一种使用企业库的 Logging Application Blocks 记录信息的方法。
引言
这是一个简单的示例应用程序,用于使用企业库的 Logging Application Block 将异常消息记录到适当的 Listener。它提供了选择记录 Listener 的选项。根据异常的级别,可以选择 Listener 类型。在应用程序意外关闭的情况下,可以将 Listener 类型设置为电子邮件和事件查看器。
当抛出异常时,捕获它并发送到此类。
它有什么作用?
- 将异常树序列化为文本。
- 此文本用作所有 Listener 类型的文本格式化程序。
- 根据所选的 Listener 类型,它将调用 Listener。
- Listener 将格式化程序作为输入,并返回适当的
TraceListener
对象。 - 将
TraceListener
对象绑定到TraceListener
列表。 - 将此 Listener 列表传递给
LogWriter
对象。 - 反过来,使用此 Listener 列表创建
LogSource
对象。 - 将此
LogWriter
对象发送到LogEntry
以记录异常信息。
如何使用?
- 将
SimpleLogger
文件添加到您的应用程序中。 - 在方法的
catch
块中调用SimpleLogger
的PublishException
方法。 - 将异常对象和
ListenerType
作为参数传递。
使用代码
在 web.config 文件中,添加 logging 库的 configsection
<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>
在 appsettings
中,为 flat 文件提供 logging 信息的文件路径
<appSettings>
<add key="logFilename" value=".\ErrorLog\Log\"/>
</appSettings>
SerializeToText 方法
在这里,循环遍历异常对象属性,获取堆栈跟踪、InnerException
信息等,并绑定到 StringBuilder
以创建 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);
//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++;
}
返回的 StringBuilder
被发送到创建 TraceListener
对象(FileTraceListener
、EmailTraceListener
或 EventLogTraceListener
中的任何一个)。
FlatFileTraceListener
private static FlatFileTraceListener GetFileTraceListener(TextFormatter formatter)
{
// Log messages to a log file.
// Use the formatter passed
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);
trace Listener 的集合被发送到 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
GetTraceSource(AddToLogSource(logListener)),
nonExistantLogSource, // LogSource allEventsTraceSource
nonExistantLogSource, // LogSource notProcessedTraceSource
AddToLogSource(logListener), // LogSource errorsTraceSource
ErrorCategory, // string defaultCategory
false, // bool tracingEnabled
true); // bool logWarningsWhenNoCategoriesMatch
PublishException
这是暴露出来用于记录信息的方法
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);
在您的 catch
块中调用此 PublishException
方法
catch(Exception ex)
{
SimpleLogger.PublishException(ex, ListenerType.EventViewer);
SimpleLogger.PublishException(ex, ListenerType.File);
SimpleLogger.PublishException(ex,ListenerType.Email);
}
结论
这是一种非常简单的记录异常信息的方式。