應用程式若需記錄重要資訊、警告或錯誤到 Windows 事件檢視器,可使用 System.Diagnostics.EventLog 類別。本文提供一個可重複使用的 LogWriter 類別,封裝事件來源建立與寫入邏輯。
using System;
using System.Diagnostics;
namespace Log
{
public class LogWriter
{
private string _eventSourceName = "TestApp";
private EventLogEntryType _eventLogType = EventLogEntryType.Error;
public string EventSourceName
{
set { _eventSourceName = value; }
}
public EventLogEntryType EventLogType
{
set { _eventLogType = value; }
}
public void LogEvent(string message)
{
if (string.IsNullOrEmpty(message)) return;
// 來源不存在時自動建立(需管理員權限)
if (!EventLog.SourceExists(_eventSourceName))
{
EventLog.CreateEventSource(_eventSourceName, "Application");
}
EventLog.WriteEntry(_eventSourceName, message, _eventLogType);
}
}
}
var logger = new LogWriter();
logger.EventSourceName = "MyService";
logger.EventLogType = EventLogEntryType.Warning;
logger.LogEvent("這是一則測試警告訊息。");
CreateEventSource 需管理員權限。建議在安裝程式或應用程式首次以管理員身分執行時預先建立來源,避免執行期拋出 SecurityException。EventLogEntryType 列舉包含 Error、Warning、Information、SuccessAudit、FailureAudit,依實際嚴重程度選擇。可進一步加入:
LogEventFormat 方法。IDisposable 釋放非受控資源(雖然 EventLog 多為靜態方法,較少需求)。