EntLib 2.0 Logging Block 重大改版:更名、支援多類別、程式碼過濾查詢、設定整合進 app.config/web.config。本文系統整理核心變更、基本用法、擴充屬性、活動追蹤、自訂 Listener/Formatter。
| 項目 | 1.1 版 | 2.0 版 |
|---|---|---|
| 名稱 | Logging & Instrumentation | Logging Application Block |
| 類別關聯 | 單一 Category | 多 Categories (logEntry.Categories.Add()) |
| 過濾查詢 | 無 | Logger.ShouldLog(logEntry) 預判是否會被記錄 |
| 設定檔 | 獨立 loggingConfiguration.config | 整合 <loggingConfiguration> 區段 |
using Microsoft.Practices.EnterpriseLibrary.Logging;
var log = new LogEntry {
EventId = 300,
Message = "Sample message",
Severity = TraceEventType.Information,
Priority = 5
};
log.Categories.Add("UI Events");
log.Categories.Add("Trace");
Logger.Write(log);
<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="...CategoryFilter"
categoryFilterMode="AllowAllExceptDenied">
<categoryFilters><add name="UI Events" /></categoryFilters>
</add>
<add name="Priority" type="...PriorityFilter" minimumPriority="2" />
<add name="LogEnabled" type="...LogEnabledFilter" enabled="true" />
</logFilters>
</loggingConfiguration>
var dict = new Dictionary<string, object>();
new ManagedSecurityContextInformationProvider().PopulateDictionary(dict);
dict.Add("Screen resolution", $"{Screen.PrimaryScreen.Bounds.Width}x{Screen.PrimaryScreen.Bounds.Height}");
Logger.Write("Log with extra info", dict);
using (new Tracer("Trace")) {
DoDataAccess();
}
void DoDataAccess() {
using (new Tracer("Data Access Events")) {
DoTroubleShooting();
}
}
void DoTroubleShooting() {
var msg = $"Simulated trouble. ActivityId={Trace.CorrelationManager.ActivityId}";
var entry = new LogEntry {
Categories = {"Troubleshooting"},
Priority = 5,
Severity = TraceEventType.Error,
Message = msg
};
Logger.Write(entry);
}
Tracer 自動管理 Trace.CorrelationManager.ActivityId,實現巢狀活動關聯。
ShouldLog 預判var entry = new LogEntry { Priority = 2 };
entry.Categories.Add("Trace");
entry.Categories.Add("UI Events");
if (Logger.ShouldLog(entry)) {
// 執行昂貴的資料蒐集 (如完整堆疊追蹤、資料庫快照)
Logger.Write(entry);
}
[ConfigurationElementType(typeof(CustomTraceListenerData))]
public class DebugTraceListener : CustomTraceListener {
public override void TraceData(TraceEventCache ec, string src, TraceEventType et, int id, object data) {
WriteLine(Formatter != null && data is LogEntry le
? Formatter.Format(le)
: data.ToString());
}
public override void Write(string msg) => Debug.Write(msg);
public override void WriteLine(string msg) => Debug.WriteLine(msg);
}
[ConfigurationElementType(typeof(CustomFormatterData))]
public class MyFormatter : ILogFormatter {
public MyFormatter(NameValueCollection attrs) { /* 解析屬性 */ }
public string Format(LogEntry log) {
// 自訂格式化邏輯
return $"{log.TimeStamp} [{log.Severity}] {log.Message}";
}
}
需將日誌輸出至 事件日誌、Email、資料庫、MSMQ、WMI、文字檔,並支援分類/優先級過濾、訊息格式化、無碼修改輸出目標的企業級應用。區塊設計為高度可擴充,適合建立標準化記錄基礎設施。