C# 最簡單 EventLog 寫入示範

安裝

在 .NET Core/.NET 上(非 .NET Framework),需要安裝 System.Diagnostics.EventLog 套件才可以使用。

先使用 NuGet 安裝 System.Diagnostics.EventLog 套件,或是使用 .NET CLI 執行以下指令安裝
	
dotnet add package System.Diagnostics.EventLog
    

註冊事件來源

註冊事件來源需要有系統管理員權限(以系統管理員身分執行),通常都會在安裝時建立:
    
string sourceName = "RuyutSource"; // 事件來源名稱
string logName = "RuyutLog"; // 日誌名稱

// 註冊事件來源
if (!EventLog.SourceExists(sourceName))
{
   EventLog.CreateEventSource(sourceName, logName);
   Console.WriteLine("事件來源已成功註冊。");
}
else
{
   Console.WriteLine("事件來源已經存在。");
}
    

若缺少系統管理員權限會出現下方的錯誤:
    
Unhandled exception. System.Security.SecurityException: The source was not found, but some or all event logs could not be searched.  Inaccessible logs: Security, State.

   at System.Diagnostics.EventLog.FindSourceRegistration(String source, String machineName, Boolean readOnly, Boolean wantToCreate)
   at System.Diagnostics.EventLog.SourceExists(String source, String machineName, Boolean wantToCreate)
   at System.Diagnostics.EventLog.SourceExists(String source, String machineName)
   at System.Diagnostics.EventLog.SourceExists(String source)
    

刪除事件來源

    
try
{
   EventLog.DeleteEventSource(sourceName);
   Console.WriteLine("事件來源已成功刪除。");
}
catch (Exception ex)
{
   Console.WriteLine("刪除事件來源時發生錯誤:" + ex.Message);
}
    

寫入事件

方法一
    
EventLog.WriteEntry(sourceName, "這是訊息1", EventLogEntryType.Information);
    

方法二
    
EventLog log = new EventLog(logName);
log.Source = sourceName;
log.WriteEntry("這是訊息2", EventLogEntryType.Information);
    

使用上面的方式寫入會在「一般」中看到「操作順利完成。」這是因為事件識別碼是 0 ,可以使用下面的寫入方式修改:
    
EventLog log = new EventLog(logName);
log.Source = sourceName;

EventLogEntryType eventType = EventLogEntryType.Information;
int eventID = 0; // 事件識別碼
short category = 1; // 工作類別
string message = "這是訊息3";

log.WriteEntry(message, eventType, eventID, category);
    



完整的錯誤代碼可以參考這篇文章

參考資料:
Microsoft.Learn - EventLog Class

留言