選中”我的電腦”,在其右鍵菜單中選擇“管理”,在打開的對話框中包括了如下圖所示的“日志”信息:
選中其中的某一條日志,可以看到如下的詳細信息:
我們應該如何通過寫代碼的方式向其中添加“日志”呢?
在操作之前,先明確幾個概念:
1:事件日志名(logName):“事件查看器”中的每一項,如“應用程序”、“Internet Explorer”、“安全性”和“系統”都是日志(嚴格地說是日志的顯示名字)
2:事件源:列表中的“來源”,創建時和事件日志相關聯;
3:事件類型:包括“信息”、“錯誤”等;
下面介紹事件日志的基本操作:
1:創建日志:我沒找到直接創建日志的方法,日志應該都是通過下面的創建事件源來間接創建;
2:創建事件源:靜態方法EventLog.CreateEventSource(string sourceName, string LogName); //參數分別表示事件源名和日志名
功能說明:在某個事件日志中創建事件源,如果事件日志不存在,則自動創建;
3:刪除日志:靜態方法EventLog.Delete(string logName);
4:刪除事件源:靜態方法EventLog.DeleteEventSource(string sourceName);
5:判斷日志是否存在:靜態方法EventLog.Exists(string logName);
6:判斷事件源是否存在:靜態方法EventLog. SourceExists (string sourceName);
7:寫日志:使用EventLog類的實例調用方法WriteEntry(string logDesc, EventLogEntryType.Information); //或者EventLogEntryType.Error
封裝的方法:
public void WriteLog(string logName, string SourceName, string LogText, EventLogEntryType type)
{
// Create an EventLog instance and assign its source.
EventLog el = new EventLog();
try
{
// Create the source, if it does not already exist.
if (!EventLog.SourceExists(SourceName))
{
if (EventLog.Exists(logName))
{
el.Log = logName;
}
else
{
EventLog.CreateEventSource(SourceName, logName);
}
}
el.Source = SourceName;
el.WriteEntry(LogText, type);
}
catch (Exception ex)
{
el.WriteEntry(ex.Message, EventLogEntryType.Error);
}
}
調用上述方法:this.WriteLog("測試日志", " testSource", " hello log ...", EventLogEntryType.Information);
執行完成之后:
雙擊右側列表中的Sources(事件源):
日志文件默認存放路徑:C:\WINDOWS\system32\config