EventLog元件
常用屬性:
Entires 取得EventLog的內容
Log 設定或寫入的EventLog名稱
Scource 設定或取得寫入到EventLog時登錄和使用的來源(source)名稱
常用方法:
Clear()
Close()
Delete()
Exists(s) 判斷名為s的記錄檔是否存在
GetEentlogs() 獲取事件記錄檔陣列
WriteEntry(s,m,t) 將來源s的訊息字串m以t型態來寫入eventlog
CreateEventSource() 建立事件檔
sourceExists() 判斷來源記綠檔是否存在
常用事件
entrywritten 項目寫入本機上的eventlog時觸發
//code ex:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
namespace EventLog_ex
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public EventLogEntryType EventType = EventLogEntryType.Information;
private void Form1_Load(object sender, EventArgs e)
{
// 指派記錄檔名稱與來源
eventLog1.Log = "MyEventLog";
eventLog1.Source = "EventLogServer";
}
//新增記錄檔
private void tSB_New_Click(object sender, EventArgs e)
{
// 建立事件記錄檔
if (!EventLog.SourceExists("EventLogServer"))
{
EventLog.CreateEventSource("EventLogServer", "MyEventLog");
MessageBox.Show(this, "MyEventLog記錄檔建立成功", "資訊");
}
else
{
MessageBox.Show(this, "建立記錄檔已經存在", "警告");
}
}
//刪除記錄檔
private void tSB_Delete_Click(object sender, EventArgs e)
{
if (EventLog.Exists("MyEventLog"))
{
EventLog.Delete("MyEventLog");
MessageBox.Show(this, "MyEventLog記錄檔已經刪除", "資訊");
}
}
//清除記錄檔項目
private void tSB_Clear_Click(object sender, EventArgs e)
{
if (EventLog.Exists("MyEventLog"))
{
eventLog1.Clear();
MessageBox.Show(this, "MyEventLog記錄檔內項目已經完全清除", "資訊");
}
}
//顯示應用程式事件記錄檔項目
private void tSB_ShowEventItem_Click(object sender, EventArgs e)
{
// 指派記錄檔名稱與來源
eventLog1.Log = "Application";
string Msg = "";
int i = 1;
if (EventLog.Exists("Application"))
{
if (eventLog1.Entries.Count > 0)
{
rTB_Info.Text = "";
foreach (EventLogEntry ELE in eventLog1.Entries)
{
Msg = Msg + "(" + i.ToString() + ") " + ELE.Message + "/r/n";
i = i + 1;
}
rTB_Info.Text = Msg;
}
}
else
{
rTB_Info.Text = "[應用程式]事件記錄檔不存在,請先新增記錄檔";
}
}
//顯示本機所有記錄檔
private void tSB_ShowAllEventLog_Click(object sender, EventArgs e)
{
EventLog[] eventLogs = EventLog.GetEventLogs();
string Msg = "";
foreach (EventLog e1 in eventLogs)
{
Msg = Msg + e1.LogDisplayName;
Msg = Msg + " , 記錄檔名稱 = " + e1.Log + "/r/n";
}
rTB_Info.Text = Msg;
}
//寫入事件記錄檔
private void tSB_WriteEventLog_Click(object sender, EventArgs e)
{
if (EventLog.Exists("MyEventLog"))
{
eventLog1.WriteEntry(tSTB_Message.Text, EventType);
MessageBox.Show(this, "MyEventLog記錄檔寫入成功", "資訊");
}
else
{
rTB_Info.Text = "MyEventLog事件記錄檔不存在,請先新增記錄檔";
}
}
private void tSCB_EventType_SelectedIndexChanged(object sender, EventArgs e)
{
switch (tSCB_EventType.SelectedIndex)
{
case 0:
EventType = EventLogEntryType.Information;
break;
case 1:
EventType = EventLogEntryType.Warning;
break;
case 2:
EventType = EventLogEntryType.Error;
break;
case 3:
EventType = EventLogEntryType.FailureAudit;
break;
case 4:
EventType = EventLogEntryType.SuccessAudit;
break;
default:
EventType = EventLogEntryType.Information;
break;
}
}
}
}