Enterprise Library2.0(2):Logging Application Block學(xué)習(xí)
摘要:Logging Application Block可以使開發(fā)人員在其應(yīng)用程序中集成日志監(jiān)測(cè)功能,看看隨著2.0的推出給我們帶來了哪些改變。
一.改進(jìn)的地方
1.Logging Application Block首先帶來的是名稱上的改變,在1.1下它的全稱應(yīng)該是Logging and Instrumentation Application Block,一般把它翻譯為日志和檢測(cè)應(yīng)用程序塊,而2.0下卻完全變成了日志應(yīng)用程序塊。
2.在1.1下,每個(gè)LogEntry只能被記錄到一個(gè)Sink,而這種情況在2.0下已經(jīng)不復(fù)存在,對(duì)于每個(gè)LogEntry對(duì)象,我們都可以通過Category指定很多的Sink。回憶一下在1.1時(shí)記錄一個(gè)日志項(xiàng):
LogEntry logEntry = new LogEntry();
logEntry.EventId = 100;
logEntry.Priority = 2;
logEntry.Message = "Informational message";
//只能設(shè)置一個(gè)
logEntry.Categorys = "UI Events";
Logger.Write(logEntry);2.0下可以添加多次:
LogEntry logEntry = new LogEntry();
logEntry.EventId = 100;
logEntry.Priority = 2;
logEntry.Message = "Informational message";
//設(shè)置多個(gè)Category
logEntry.Categories.Add("Trace");
logEntry.Categories.Add("UI Events");
Logger.Write(logEntry);
3.可以在代碼中查詢哪些日志項(xiàng)將被過濾,例如:
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下關(guān)于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.添加相關(guān)的引用
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.創(chuàng)建一個(gè)日志項(xiàng)
LogEntry log = new LogEntry();
log.EventId = 300;
log.Message = "Sample message";
log.Categories.Add("UI Events");
log.Severity = TraceEventType.Information;
log.Priority = 5;
3.調(diào)用Logger.Write()方法
Logger.Write(log);三.記錄日志項(xiàng)的擴(kuò)展屬性
使用基于泛型的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);
四.跟蹤活動(dòng)并記錄上下文信息
1.調(diào)用DoDataAccess方法,完成后釋放Trace對(duì)象
using (new Tracer("Trace"))
{
DoDataAccess();
}
2.創(chuàng)建DoDataAccess方法
private void DoDataAccess()
{
using (new Tracer("Data Access Events"))
{
// Peform work here
// Assume an error condition was detected - perform some troubleshooting.
DoTroubleShooting();
}
}
3.創(chuàng)建另一個(gè)方法DoTroubleShooting,并在其中創(chuàng)建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);
}五.檢測(cè)日志項(xiàng)是否被記錄
創(chuàng)建一個(gè)日志項(xiàng)并設(shè)置它的信息,調(diào)用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.
}
六.創(chuàng)建自定義的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);
}
七.創(chuàng)建自定義的Formatter
1.在自定義的類上添加特性ConfigurationElementType,并實(shí)現(xiàn)接口ILogFormatter
[ConfigurationElementType(typeof(CustomFormatterData))]
public class MyFormatter : ILogFormatter
{
//
}
2.構(gòu)造函數(shù)接受一個(gè)類型為NameValueCollection的參數(shù)
public MyFormatter (NameValueCollection attributes)
{
//
}
3.添加Format方法,它接受一個(gè)LogEntry的參數(shù)
public string Format(LogEntry log)
{
//
}
八.使用場(chǎng)景
如果你的應(yīng)用程序需要挾日志到Event Log, E-mail, Database, Message Queue, Windows Management Instrumentation (WMI), TextFile,你就應(yīng)該考慮使用日志組件來提供這些功能,特別如果你需要基于分類和優(yōu)先級(jí)來過濾日志消息,需要格式化消息,或者需要不改動(dòng)代碼的情況下改變消息的目的地。日志組件同時(shí)被設(shè)計(jì)成可擴(kuò)展的,包括方便的創(chuàng)建客戶訂制的Formatter和TraceListener。
參考資料:Enterprise Libaray –January 2006幫助文檔
Worktile,新一代簡單好用、體驗(yàn)極致的團(tuán)隊(duì)協(xié)同、項(xiàng)目管理工具,讓你和你的團(tuán)隊(duì)隨時(shí)隨地一起工作。完全免費(fèi),現(xiàn)在就去了解一下吧。
https://worktile.com



浙公網(wǎng)安備 33010602011771號(hào)