.NET System.Diagnostics.EventLog 提供寫入 Windows 事件檢視器的功能,適用於服務、背景作業、關鍵錯誤審計。本文提供可直接使用的 LogWriter 封裝類別,支援自訂事件來源、日誌類型(Error/Warning/Information),並自動建立事件來源。
using System.Diagnostics;
public class LogWriter
{
private string _source = "MyApp";
private EventLogEntryType _type = EventLogEntryType.Error;
public string EventSourceName { set => _source = value; }
public EventLogEntryType EventLogType { set => _type = value; }
public void LogEvent(string message)
{
if (!EventLog.SourceExists(_source))
{
// 需管理員權限,建議安裝時由安裝程式建立
EventLog.CreateEventSource(_source, "Application");
}
EventLog.WriteEntry(_source, message, _type);
}
}
var logger = new LogWriter { EventSourceName = "OrderService", EventLogType = EventLogEntryType.Warning };
logger.LogEvent("訂單 #12345 庫存不足,已觸發補貨流程。");
// 直接寫入靜態方法(無需實例)
EventLog.WriteEntry("MyApp", "應用程式啟動", EventLogEntryType.Information);
| 主題 | 說明 |
|---|---|
| 事件來源 | 唯一識別應用程式/元件,建議「公司.產品.模組」格式。SourceExists/CreateEventSource 需管理員權限,部署階段由安裝腳本建立,執行期勿嘗試建立。 |
| 日誌類型 | Error(紅)、Warning(黃)、Information(藍)、SuccessAudit/FailureAudit(安全審計)。 |
| 日誌名稱 | 預設 "Application",亦可 "System"、"Security"(需高權限)、自訂日誌。 |
| 訊息長度 | 單一項目上限 32KB,超長訊息會被截斷;大量資料改寫檔案/資料庫,日誌僅記錄摘要與參考 ID。 |
| 效能 | 同步寫入、跨程序通訊,頻繁呼叫會影響效能;高頻場景改用 ETW (EventSource)、Serilog/NLog 非同步寫入檔案/Seq/Elasticsearch。 |
| 遠端讀取 | EventLog.GetEventLogs("serverName") 讀取遠端機器日誌(需 RPC/防火牆開放)。 |
.NET Core / .NET 5+ 推薦使用 System.Diagnostics.Tracing.EventSource(ETW 提供者),支援結構化欄位、高效能、PerfView/Windows Performance Analyzer 分析:
[EventSource(Name = "MyCompany-MyApp")]
public sealed class MyEventSource : EventSource
{
public static MyEventSource Log = new MyEventSource();
[Event(1, Level = EventLevel.Warning)]
public void LowInventory(int orderId, string sku) => WriteEvent(1, orderId, sku);
}
// 使用:MyEventSource.Log.LowInventory(12345, "SKU-001");
正確使用系統事件日誌,能讓系統異常在「事件檢視器」留下可追溯、可篩選、可告警的審計軌跡。