Windows 事件日誌是應用程式記錄錯誤、警告、資訊的標準機制。C# System.Diagnostics.EventLog 提供完整操作 API。本文封裝可重用的 LogWriter 類別,支援自訂事件來源、日誌類型,並處理來源自動註冊。
using System;
using System.Diagnostics;
namespace Log
{
public class LogWriter
{
private string _eventSourceName = "test";
private EventLogEntryType _eventLogType = EventLogEntryType.Error;
public string EventSourceName
{
set => _eventSourceName = value;
}
public EventLogEntryType EventLogType
{
set => _eventLogType = value;
}
public void LogEvent(string message)
{
// 來源不存在時自動建立(需管理員權限)
if (!EventLog.SourceExists(_eventSourceName))
{
EventLog.CreateEventSource(_eventSourceName, "Application");
}
EventLog.WriteEntry(_eventSourceName, message, _eventLogType);
}
}
}
var logger = new LogWriter
{
EventSourceName = "MyApp",
EventLogType = EventLogEntryType.Warning
};
logger.LogEvent("資料庫連線失敗,重試中...");
| 點 | 說明 |
|---|---|
| 來源註冊 | EventLog.CreateEventSource 需管理員權限,建議安裝程式或啟動時執行一次 |
| 日誌類型 | EventLogEntryType:Error、Warning、Information、SuccessAudit、FailureAudit |
| 寫入目標 | 預設寫入「Application」日誌,亦可指定自訂日誌名稱 |
| 遠端寫入 | EventLog.WriteEntry("Source", "Msg", type, 123, "RemoteMachine") |
| 讀取日誌 | new EventLog("Application").Entries 列舉 EventLogEntry |
CreateEventSource,運行期僅寫入。EventLog.WriteEntryAsync (.NET 4.6+) 或批次寫入,避免阻塞主執行緒。EventLog 是 Windows 平台原生、零依賴的日誌方案,適合簡單應用、服務、定時任務。LogWriter 封裝提供來源管理、類型選擇、自動註冊等實用功能。企業級系統建議遷移至結構化日誌框架,但理解 EventLog 基礎操作仍是 .NET 開發者必備技能。