首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

Enterprise Library 2.0 學習筆記 (二):Logging Application Block 完整指南

     編輯:關於.NET

EntLib 2.0 Logging Block 重大改版:更名、支援多類別、程式碼過濾查詢、設定整合進 app.config/web.config。本文系統整理核心變更、基本用法、擴充屬性、活動追蹤、自訂 Listener/Formatter。

核心改進對比

項目1.1 版2.0 版
名稱Logging & InstrumentationLogging 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);

設定檔範例 (app.config)

<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>

擴充屬性:Dictionary 傳遞任意資訊

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);
}

自訂 TraceListener

[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);
}

自訂 Formatter

[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、文字檔,並支援分類/優先級過濾、訊息格式化、無碼修改輸出目標的企業級應用。區塊設計為高度可擴充,適合建立標準化記錄基礎設施。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved