一.改進的地方
1.Logging Application Block首先帶來的是名稱上的改變,在1.1下它的全稱應該是Logging and Instrumentation Application Block,一般把它翻譯為日志和檢測應用程序塊,而2.0下卻完全變成了日志應用程序塊。
2.在1.1下,每個LogEntry只能被記錄到一個Sink,而這種情況在2.0下已經不復存在,對於每個LogEntry對象,我們都可以通過Category指定很多的Sink。回憶一下在1.1時記錄一個日志項:
LogEntry logEntry = new LogEntry();
2.0下可以添加多次:
logEntry.EventId = 100;
logEntry.Priority = 2;
logEntry.Message = "Informational message";
//只能設置一個
logEntry.Categorys = "UI Events";
Logger.Write(logEntry);
LogEntry logEntry = new LogEntry();
logEntry.EventId = 100;
logEntry.Priority = 2;
logEntry.Message = "Informational message";
//設置多個Category
logEntry.Categories.Add("Trace");
logEntry.Categories.Add("UI Events");
Logger.Write(logEntry);
3.可以在代碼中查詢哪些日志項將被過濾,例如:
LogEntry logEntry = new LogEntry();
logEntry.Priority = 2;
logEntry.Categories.Add("Trace");
logEntry.Categories.Add("UI Events");
if (Logger.ShouldLog(logEntry))
{
// Event will be logged according to currently configured filters.
}
else
{
// Event will not be logged.
}
4.配置文件的改變。在1.1下關於Logging & Instrumentation Application Block的信息記錄在loggingconfiguration.config文件中,2.0下所有的信息都放在了Web.config或App.config中,如:
<configuration>
<configSections>
<section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging" />
</configSections>
<loggingConfiguration tracingEnabled="true" defaultCategory="General">
<logFilters>
<add
name="Category"
type="Microsoft.Practices.EnterpriseLibrary.Logging.Filters.CategoryFilter, Microsoft.Practices.EnterpriseLibrary.Logging"
categoryFilterMode="AllowAllExceptDenied">
<categoryFilters>
<add name="UI Events" />
</categoryFilters>
</add>
<add
name="Priority"
type="Microsoft.Practices.EnterpriseLibrary.Logging.Filters.PriorityFilter, Microsoft.Practices.EnterpriseLibrary.Logging"
minimumPriority="2"
/>
<add name="LogEnabled Filter"
type="Microsoft.Practices.EnterpriseLibrary.Logging.Filters.LogEnabledFilter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null"
enabled="true"
/>
</logFilters>
</loggingConfiguration>
</configuration>
二.記錄日志信息
1.添加相關的引用
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using Microsoft.Practices.EnterpriseLibrary.Logging.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging.ExtraInformation;
using Microsoft.Practices.EnterpriseLibrary.Logging.Filters;
2.創建一個日志項
LogEntry log = new LogEntry();
log.EventId = 300;
log.Message = "Sample message";
log.Categories.Add("UI Events");
log.Severity = TraceEventType.Information;
log.Priority = 5;
3.調用Logger.Write()方法
Logger.Write(log);
三.記錄日志項的擴展屬性
使用基於泛型的Dictionary來記錄,如下
// Create the dictionary to hold the extra information, and populate it
// with managed security information.
Dictionary<string, object> dictionary = new Dictionary<string, object>();
ManagedSecurityContextInformationProvider informationHelper = new ManagedSecurityContextInformationProvider();
informationHelper.PopulateDictionary(dictionary);
// Add a custom property for screen resolution
int width = Screen.PrimaryScreen.Bounds.Width;
int height = Screen.PrimaryScreen.Bounds.Height;
string resolution = String.Format("{0}x{1}", width, height);
dictionary.Add("Screen resolution", resolution);
// Write the log entry that contains the extra information
Logger.Write("Log entry with extra information", dictionary);
四.跟蹤活動並記錄上下文信息
1.調用DoDataAccess方法,完成後釋放Trace對象
using (new Tracer("Trace"))
{
DoDataAccess();
}
2.創建DoDataAccess方法
private void DoDataAccess()
{
using (new Tracer("Data Access Events"))
{
// Peform work here
// Assume an error condition was detected - perform some troubleshooting.
DoTroubleShooting();
}
}
3.創建另一個方法DoTroubleShooting,並在其中創建LogEntry。
private void DoTroubleShooting()
{
string logMessage = "Simulated troubleshooting message for Logging QuickStart. " +
"Current activity=\"" + Trace.CorrelationManager.ActivityId + "\"";
LogEntry logEntry = new LogEntry();
logEntry.Categories.Clear();
logEntry.Categories.Add("Troubleshooting");
logEntry.Priority = 5;
logEntry.Severity = TraceEventType.Error;
logEntry.Message = logMessage;
Logger.Write(logEntry);
}
五.檢測日志項是否被記錄
創建一個日志項並設置它的信息,調用Logger.ShouldLog()方法
LogEntry logEntry = new LogEntry();
logEntry.Priority = 2;
logEntry.Categories.Add("Trace");
logEntry.Categories.Add("UI Events");
if (Logger.GetFilter<CategoryFilter>().ShouldLog(logEntry))
{
// Event will be logged according to currently configured filters.
// Perform operations (possibly expensive) to gather additional information
// for the event to be logged.
}
else
{
// Event will not be logged. Your application can avoid the performance
// penalty of collecting information for an event that will not be
// logged.
}
LogEntry logEntry = new LogEntry();
logEntry.Priority = 2;
logEntry.Categories.Add("Trace");
logEntry.Categories.Add("UI Events");
if (Logger.ShouldLog(logEntry))
{
// Event will be logged according to currently configured filters.
}
else
{
// Event will not be logged.
}
六.創建自定義的Trace Listener
1.添加特性ConfigurationElementType,需要繼承自CustomTraceListener
[ConfigurationElementType(typeof(CustomTraceListenerData))]
public class DebugTraceListener : CustomTraceListener
{
//
}
2.覆寫TraceData方法
public override void TraceData(TraceEventCache eventCache, string source, TraceEventType eventType, int id, object data)
{
if (data is LogEntry && this.Formatter != null)
{
this.WriteLine(this.Formatter.Format(data as LogEntry));
}
else
{
this.WriteLine(data.ToString());
}
}
3.覆寫Write()和WriteLine()方法
/**//// <summary>
/// Writes a message to the debug window
/// </summary>
/// <param name="message">The string to write to the debug window</param>
public override void Write(string message)
{
Debug.Write(message);
}
/**//// <summary>
/// Writes a message to the debug window
/// </summary>
/// <param name="message">The string to write to the debug window</param>
public override void WriteLine(string message)
{
Debug.WriteLine(message);
}
七.創建自定義的Formatter
1.在自定義的類上添加特性ConfigurationElementType,並實現接口ILogFormatter
[ConfigurationElementType(typeof(CustomFormatterData))]
public class MyFormatter : ILogFormatter
{
//
}
2.構造函數接受一個類型為NameValueCollection的參數
public MyFormatter (NameValueCollection attributes)
{
//
}
3.添加Format方法,它接受一個LogEntry的參數
public string Format(LogEntry log)
{
//
}
八.使用場景
如果你的應用程序需要挾日志到Event Log, E-mail, Database, Message Queue, Windows Management Instrumentation (WMI), TextFile,你就應該考慮使用日志組件來提供這些功能,特別如果你需要基於分類和優先級來過濾日志消息,需要格式化消息,或者需要不改動代碼的情況下改變消息的目的地。日志組件同時被設計成可擴展的,包括方便的創建客戶訂制的Formatter和TraceListener。