在先前的技巧(1)與(2)中,我們分別介紹了使用外部設定檔與資料庫儲存組態資訊的做法。但你是否想過,完全不依賴任何設定檔或資料庫,直接透過程式碼來配置 Logging Application Block?本文將示範如何以程式設計方式完成 Logging Application Block 的設定。
LogFormatter 負責將日誌項目格式化為特定輸出格式,主要有 TextFormatter 與 BinaryFormatter 兩種,實務上最常用的是 TextFormatter。它透過一個 Template 字串來建立,完整的 Template 範例如下:
Timestamp: {timestamp}{newline}
Message: {message}{newline}
Category: {category}{newline}
Priority: {priority}{newline}
EventId: {eventid}{newline}
Severity: {severity}{newline}
Title:{title}{newline}
Machine: {machine}{newline}
Application Domain: {appDomain}{newline}
Process Id: {processId}{newline}
Process Name: {processName}{newline}
Win32 Thread Id: {win32ThreadId}{newline}
Thread Name: {threadName}{newline}
Extended Properties: {dictionary({key} - {value})}{newline}
各佔位符含義請參考官方文件。實際建立範例:
const string Template = "Timestamp: {timestamp}{newline}" +
"Message: {message}{newline}" +
"Category: {category}{newline}" +
"Machine: {machine}{newline}";
TextFormatter formatter = new TextFormatter(Template);
TraceListener 決定日誌寫入的目的地,Enterprise Library 2.0 內建 7 種:
每種 TraceListener 都需要一個 LogFormatter 來格式化輸出內容。以下示範建立一個寫入文字檔的 FlatFileTraceListener:
const string LogFilePath = @"d:\share\messages.log";
FlatFileTraceListener logFileListener =
new FlatFileTraceListener(LogFilePath, "----------", "----------", formatter);
此處的 formatter 即為前述建立的 TextFormatter 物件。
LogSource 本質上是 TraceListener 的集合。Enterprise Library 允許針對不同類別的日誌導向不同目的地,因此可在一個 LogSource 中加入多個 TraceListener:
LogSource mainLogSource = new LogSource("MainLogSource", SourceLevels.All);
mainLogSource.Listeners.Add(logFileListener);
透過上述三個核心物件的組合,即可完全以程式碼方式配置 Logging Application Block,無需任何 XML 設定檔,極大提升部署彈性與程式可控性。