應用系統的開發與維護離不開日誌系統。在 Windows 環境下,除了自建文字日誌檔、資料庫日誌、log4net/Serilog 等第三方框架,Windows 事件日誌 是原生、結構化、具備檢視器與管理工具的最佳選擇。本文系統說明如何在 .NET (Framework/Core) 中使用 System.Diagnostics.EventLog 寫入事件日誌,重點解決 Web 應用 (ASP.NET/ASP.NET Core) 權限不足無法建立事件來源 的三大方案。
寫入流程:EventLog.CreateEventSource(source, logName) → `new EventLog(logName) { Source = source }` → `WriteEntry(message, type)`。
using System.Diagnostics;
public static class EventLogHelper
{
private const string DefaultLogName = "MyAppLog"; // 自訂日誌名稱
public static void Write(string source, string message, EventLogEntryType type = EventLogEntryType.Information)
{
EnsureSourceExists(source);
using (var log = new EventLog(DefaultLogName) { Source = source })
{
log.WriteEntry(message, type);
}
}
private static void EnsureSourceExists(string source)
{
if (!EventLog.SourceExists(source))
{
// 需管理員權限,Web 環境請參考下方三大方案
EventLog.CreateEventSource(source, DefaultLogName);
}
}
}
// 呼叫範例
EventLogHelper.Write("WebLog", "使用者登入成功", EventLogEntryType.Information);
EventLogHelper.Write("WebLog", "資料庫連線失敗", EventLogEntryType.Error);
| 類型 | Enum 值 | 適用情境 |
|---|---|---|
| Error | EventLogEntryType.Error | 功能失敗、資料遺失、例外錯誤 |
| Warning | EventLogEntryType.Warning | 潛在問題、效能下降、重試成功 |
| Information | EventLogEntryType.Information | 關鍵業務流程完成、啟動/關閉 |
| SuccessAudit | EventLogEntryType.SuccessAudit | 登入成功、權限授予、關鍵操作審計 |
| FailureAudit | EventLogEntryType.FailureAudit | 登入失敗、存取被拒、安全違規 |
問題:ASP.NET 執行身分 (IIS 6.0: ASPNET / IIS 7+: ApplicationPoolIdentity) 預設無寫入登錄表權限,呼叫 CreateEventSource 會拋出 SecurityException: Requested registry access is not allowed。
New-EventLog -LogName "MyAppLog" -Source "WebLog"EventLogInstaller 專案(見下),打包進 MSI,安裝時自動建立。
// 專案類型:Class Library,參考 System.Configuration.Install
[RunInstaller(true)]
public class MyEventLogInstaller : Installer
{
public MyEventLogInstaller()
{
var installer = new EventLogInstaller
{
Source = "WebLog",
Log = "MyAppLog"
};
Installers.Add(installer);
}
}
建置產生 DLL,部署時以管理員執行 InstallUtil MyEventLogInstaller.dll 即可註冊來源。
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\EventlogIIS AppPool\YourAppPoolName → 授予 讀取/寫入。風險:賦予應用程式池寫入事件日誌登錄表權限,若網站被攻破,攻擊者可竄改/清除系統日誌。生產環境請優先採方案 A 或 B。
EventLog 僅支援 Windows。Linux/Docker 環境需改用 Microsoft.Extensions.Logging.EventLog (僅 Windows) 或串接 Syslog/Elasticsearch/Seq 等集中式日誌。AddEventLog() 於 `Program.cs`,統一使用 `ILogger` 介面,避免直接依賴 `EventLog` 類別。善用 Windows 事件日誌,能讓系統日誌與作業系統原生管理工具無縫整合,無論是事件檢視器、PowerShell `Get-WinEvent`、還是 SIEM 收集器都能直接處理。掌握 EventLog 寫入與來源註冊權限分離,是 .NET 開發者邁向專業運維的關鍵技能。