System.Diagnostics.EventLog 類別讓 .NET 應用程式能直接寫入 Windows 事件檢視器,無需額外日誌框架即可實現系統級日誌記錄。本文示範基礎寫入、自訂事件來源、多事件日誌管理與查詢操作。
using System.Diagnostics;
EventLog log = new EventLog();
try
{
log.Source = "我的應用程式";
log.WriteEntry("處理資訊 1", EventLogEntryType.Information);
log.WriteEntry("處理資訊 2", EventLogEntryType.Information);
throw new System.IO.FileNotFoundException("readme.txt 檔案未找到");
}
catch (System.IO.FileNotFoundException ex)
{
log.WriteEntry(ex.Message, EventLogEntryType.Error);
}
關鍵點:
Source 屬性識別事件來源,需在首次寫入前設定EventLogEntryType 列舉:Information、Warning、Error、SuccessAudit、FailureAudit非 Application 日誌需先建立事件來源(需管理員權限):
EventLog log = new EventLog("System");
if (!EventLog.SourceExists("My Application"))
{
EventLog.CreateEventSource("My Application", "System");
}
log.Source = "My Application";
log.WriteEntry("系統級資訊", EventLogEntryType.Information);
log.WriteEntry("嚴重錯誤", EventLogEntryType.Error);
注意: 一個事件來源同一時間只能繫結一個事件日誌。若來源已存在於其他日誌,CreateEventSource 會拋出例外。
EventLog log = new EventLog("MyCustomLog");
if (!EventLog.SourceExists("MyAppSource"))
{
EventLog.CreateEventSource("MyAppSource", "MyCustomLog");
}
log.Source = "MyAppSource";
log.WriteEntry("自訂日誌記錄", EventLogEntryType.Information);
執行後可在事件檢視器左側看到新增的 MyCustomLog 節點,適合應用程式專用日誌隔離。
// 列舉指定日誌所有記錄
if (EventLog.Exists("MyCustomLog"))
{
EventLog log = new EventLog("MyCustomLog");
foreach (EventLogEntry entry in log.Entries)
{
Console.WriteLine($"[{entry.EntryType}] {entry.TimeGenerated}: {entry.Message}");
}
}
// 刪除自訂日誌與來源
EventLog.Delete("MyCustomLog");
EventLog.DeleteEventSource("MyAppSource");
EventLog 支援 machineName 建構子參數讀取遠端電腦日誌(需權限)。