[C#.NET][VB.NET] 事件記錄簿 / EventLog
.NET Framework 2.0以上就提供了讀寫事件記錄簿的功能,好讓已上機工作的程式將錯誤訊息記錄下來,當然也不一定要用事件記錄簿來記錄,只是.NET有提供這一個功能,至於應用方面,還是得靠自己的經驗實務來累積呢。不過事件記錄簿還是有一些使用上的限制,http://msdn.microsoft.com/zh-tw/library/system.diagnostics.eventlog(VS.80).aspx
using System.Diagnostics 命名空間
如何建立記錄
1.類別實體化,建立一個事件記錄器
EventLog DemoLog = new EventLog("Application");
2.指定來源名稱,必須與實體化名稱相同
DemoLog.Source = "Demo";
3.寫入事件訊息
DemoLog.WriteEntry("A DemoService Restarted due to reboot", EventLogEntryType.Information); 
如何讀取事件記錄
1.類別實體化,建立一個事件記錄器
EventLog DemoLog = new EventLog("System");
2.讀取資料
3.印出資料
foreach (EventLogEntry DemoEntry in DemoLog.Entries)
{    
    Console.WriteLine(DemoEntry.Source + ":" + DemoEntry.Message);    
    this.listBox1.Items.Add(DemoEntry.Source + ":" + DemoEntry.Message);    }
如何建立事件簿
string mySource = "DemoLog";
string myLog = "MyNewLog";
string com = ".";
try      
{      
    EventLog.DeleteEventSource(mySource, com);      }
catch (Exception)      
{       }
finally       
{      
    EventLog.CreateEventSource(mySource, myLog,com);      }
EventLog elog = new EventLog(myLog, com);      elog.Source = mySource;
elog.WriteEntry("A DemoService Restarted due to reboot", EventLogEntryType.Information, 234, Convert.ToInt16(3));
如何刪除事件記錄
try    
{    
    EventLog.Delete("MyNewLog");    }
catch (Exception ex)    
{    
    Console.WriteLine(ex.Message.ToString());    }
因為懶的判斷事件記錄簿存不存在,所以就用try..catch攔截
範例下載:C#.NET 事件記錄簿.rar
若有謬誤,煩請告知,新手發帖請多包涵
Microsoft MVP Award 2010~2017 C# 第四季
Microsoft MVP Award 2018~2022 .NET