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

C# 3.0 實戰:使用 EventLog 類別寫入 Windows 事件日誌

     編輯:關於C#

System.Diagnostics.EventLog 類別讓 .NET 應用程式能直接寫入 Windows 事件檢視器,無需額外日誌框架即可實現系統級日誌記錄。本文示範基礎寫入、自訂事件來源、多事件日誌管理與查詢操作。

基本寫入:Application 事件日誌


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

關鍵點:

  • 預設寫入 Application 事件日誌
  • Source 屬性識別事件來源,需在首次寫入前設定
  • EventLogEntryType 列舉:Information、Warning、Error、SuccessAudit、FailureAudit

寫入 System 等內建日誌:需先註冊事件來源

非 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");

實務注意事項

  • 權限:建立事件來源需管理員權限,建議安裝程式階段完成,執行期僅寫入。
  • 效能:頻繁寫入事件日誌有額外開銷,高頻日誌建議使用專用框架(Serilog、NLog)搭配 EventLog 接收器。
  • 日誌大小:事件日誌有大小上限,滿時會覆蓋或停止記錄。可在事件檢視器屬性中調整最大容量或設定自動覆蓋。
  • 遠端存取:EventLog 支援 machineName 建構子參數讀取遠端電腦日誌(需權限)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved