如何管理使用 Visual C#.NET 或 Visual C# 2005年的事件記錄檔

文章翻譯 文章翻譯
文章編號: 815314 - 檢視此文章適用的產品。
本文章的有 Microsoft Visual Basic.NET] 版本請參閱 814564
全部展開 | 全部摺疊

在此頁中

結論

本文將逐步告訴您,如何存取和自訂使用 Microsoft.NET Framework 的 Windows 事件記錄檔。與 EventLog 類別您可以與 Windows 事件記錄檔互動。使用您可以從現有的記錄檔讀取的 EventLog 類別,項目寫入事件記錄檔、 建立或刪除事件來源、 刪除記錄檔,及回應記錄項目。本文也將告訴您如何建立事件來源時建立新的記錄檔。

需求

下列清單列出建議的硬體、 軟體、 網路基礎結構及所需的 Service Pack:
  • Microsoft.NET Framework
  • Microsoft Visual C#.NET 或 Microsoft Visual C# 2005。
本文假設您已熟悉下列主題:
  • Microsoft Visual C#.NET 或 Microsoft Visual C# 2005年的語法
  • Microsoft Visual Studio.NET 或 Microsoft Visual Studio 2005 環境
  • .NET Framework 中的錯誤處理

在電腦上找到現有的記錄檔


您可以使用共用的方法 GetEventLogsEventLog 類別的在電腦上尋找現有的記錄檔。GetEventLogs 方法搜尋本機電腦上的所有事件記錄檔,並建立包含清單的 EventLog 物件陣列。下列範例會擷取本機電腦上的記錄檔的清單,,然後在主控台視窗中顯示記錄檔的名稱。
EventLog[] remoteEventLogs; 
// Gets logs on the local computer, gives remote computer name to get the logs on the remote computer.
remoteEventLogs = EventLog.GetEventLogs(System.Environment.MachineName);
Console.WriteLine("Number of logs on computer: " + remoteEventLogs.Length);

for ( int i=0; i<remoteEventLogs.Length; i++ )
   Console.WriteLine("Log: " + remoteEventLogs[i].Log);

讀取和寫入本機和遠端系統記錄檔

讀取記錄檔

若要讀取事件記錄檔,使用 [EventLog 類別的 項目 屬性]。EventLog 類別 項目 屬性是在事件記錄檔中的所有項目集合。您可以逐一查看這個集合和讀取指定的記錄檔中的所有項目。下列程式碼會示範如何執行這項操作:
      
//logType can be Application, Security, System or any other Custom Log.
string logType = "Application";
			
EventLog ev = new EventLog(logType, System.Environment.MachineName);
int LastLogToShow = ev.Entries.Count;
if ( LastLogToShow <= 0 )
Console.WriteLine("No Event Logs in the Log :" + logType);

// Read the last 2 records in the specified log. 
int i;
for ( i = ev.Entries.Count - 1; i>= LastLogToShow - 2; i--)
{
	EventLogEntry CurrentEntry = ev.Entries[i];
	Console.WriteLine("Event ID : " + CurrentEntry.EventID);
	Console.WriteLine("Entry Type : " + CurrentEntry.EntryType.ToString());
	Console.WriteLine("Message :  " + CurrentEntry.Message + "\n");
}	
ev.Close();

寫入記錄檔

若要編寫事件日誌,使用 的話,WriteEntry 方法的 EventLog 類別。要成功地寫入事件記錄檔,您的應用程式必須具有嘗試要寫入記錄檔的寫入權限。如需有關權限,您必須要有讀取和寫入事件記錄檔中的詳細資訊,請造訪下列 Microsoft 網站]。
事件記錄檔的安全性 Ramification
http://msdn2.microsoft.com/en-us/library/4xz6w79h(vs.71).aspx
項目寫入記錄檔之前,必須在 EventLog 元件執行個體上設定 [來源] 屬性。當您的元件寫入一個項目時,系統自動驗證以查看您所指定的來源是否已登錄與事件記錄檔寫入至,元件,和元件 (如果必須呼叫 CreateEventSource),然後呼叫 CreateEventSource
  
//See if the source exists. 
if ( ! ( EventLog.SourceExists("MySystemSource", System.Environment.MachineName)))
EventLog.CreateEventSource("MySystemSource", "System", System.Environment.MachineName);
        
EventLog ev = new EventLog("System", System.Environment.MachineName, "MySystemSource");
/* Writing to system log, in the similar way you can write to other 
 * logs that you have appropriate permissions to write to
 */
ev.WriteEntry("Warning is written to system Log", EventLogEntryType.Warning, 10001);
MessageBox.Show("Warning is written to System Log");
ev.Close();   

清除記錄檔

事件記錄檔已滿時, 它會停止記錄新的事件資訊,或開始覆寫較早的項目。如果事件錄製會停止,您就可以清除記錄檔中的現有項目,並允許重新開始錄製事件記錄檔。事件記錄檔元件執行個體上呼叫 Clear 方法。

附註若要清除 [事件日誌項目,您必須在電腦上擁有系統管理員權限位置記錄檔便是
     
//Create an EventLog instance and pass log name and MachineName where the log resides.
EventLog ev = new EventLog("Security", System.Environment.MachineName);
ev.Clear();
ev.Close(); 

建立和刪除自訂記錄檔

建立自訂記錄檔

CreateEventSource 方法可用來建立您自己的自訂事件處理常式。建立事件記錄檔之前請確認您所使用的來源不會還沒存在,及呼叫 CreateEventSource 使用 SourceExists 方法。如果嘗試建立已經存在的事件記錄檔就會擲回 System.ArgumentException
     
// Create the source, if it does not already exist.
if (! (EventLog.SourceExists("MyOldSource", System.Environment.MachineName)))
		EventLog.CreateEventSource("MyOldSource", "MyNewLog", System.Environment.MachineName);
Console.WriteLine("CreatingEventSource"); 

刪除自訂記錄檔

若要刪除事件記錄檔,您可以使用 EventLog 類別的 Delete 方法。多個來源可能會將寫入至事件記錄檔。因此,刪除自訂記錄檔之前請確定有沒有其他來源寫入該記錄檔。
     
string logName = "MyNewLog";
if ( EventLog.SourceExists("MyOldSource", System.Environment.MachineName))
{
	logName = EventLog.LogNameFromSourceName("MyOldSource", System.Environment.MachineName);
	EventLog.DeleteEventSource("MyOldSource", System.Environment.MachineName);
	EventLog.Delete(logName, System.Environment.MachineName);
	Console.WriteLine(logName + " deleted.");
}    

接收事件通知

項目寫入特定的記錄檔時,您可以接收事件告知。若要執行此動作實作 EventLog 之執行個體的 [EntryWritten 事件處理常式]。而且,將 EnableRaisingEvents 設定為 true

附註項目寫入本機電腦上,只會收到事件通知。您無法接收通知寫入遠端電腦上的項目。

完成程式碼程式碼範例

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Security;
using System.IO;
using System.Diagnostics;

namespace WindowsApplication1
{
	/// <summary>
	/// Summary description for Form1.
	/// </summary>
	public class Form1 : System.Windows.Forms.Form
	{
		private System.Diagnostics.EventLog eventLog1;
		private System.Windows.Forms.Button btnListLog;
		private System.Windows.Forms.Button btnReadLog;
		private System.Windows.Forms.Button btnWriteLog;
		private System.Windows.Forms.Button btnClearLog;
		private System.Windows.Forms.Button btnCreateLog;
		private System.Windows.Forms.Button btnDeleteLog;
		private System.Windows.Forms.Button btnRecNotice;
		
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.Container components = null;

		public Form1()
		{
			//
			// Required for Windows Form Designer support.
			//
			InitializeComponent();

			//
			// TODO: Add any constructor code after InitializeComponent call.
			//
		}

		/// <summary>
		/// Clean up any resources that are being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if (components != null) 
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.eventLog1 = new System.Diagnostics.EventLog();
			this.btnListLog = new System.Windows.Forms.Button();
			this.btnReadLog = new System.Windows.Forms.Button();
			this.btnWriteLog = new System.Windows.Forms.Button();
			this.btnClearLog = new System.Windows.Forms.Button();
			this.btnCreateLog = new System.Windows.Forms.Button();
			this.btnDeleteLog = new System.Windows.Forms.Button();
			this.btnRecNotice = new System.Windows.Forms.Button();
			((System.ComponentModel.ISupportInitialize)(this.eventLog1)).BeginInit();
			this.SuspendLayout();
			// 
			// eventLog1
			// 
			this.eventLog1.MachineName = System.Environment.MachineName;
			this.eventLog1.SynchronizingObject = this;
			this.eventLog1.EntryWritten += new System.Diagnostics.EntryWrittenEventHandler(this.eventLog1_EntryWritten);

			// 
			// btnListLog
			// 
			this.btnListLog.Location = new System.Drawing.Point(32, 16);
			this.btnListLog.Name = "btnListLog";
			this.btnListLog.Size = new System.Drawing.Size(152, 23);
			this.btnListLog.TabIndex = 0;
			this.btnListLog.Text = "List Event Logs";
			this.btnListLog.Click += new System.EventHandler(this.btnListLog_Click);
			// 
			// btnReadLog
			// 
			this.btnReadLog.Location = new System.Drawing.Point(32, 46);
			this.btnReadLog.Name = "btnReadLog";
			this.btnReadLog.Size = new System.Drawing.Size(152, 23);
			this.btnReadLog.TabIndex = 1;
			this.btnReadLog.Text = "Read Event Logs";
			this.btnReadLog.Click += new System.EventHandler(this.btnReadLog_Click);
			// 
			// btnWriteLog
			// 
			this.btnWriteLog.Location = new System.Drawing.Point(32, 77);
			this.btnWriteLog.Name = "btnWriteLog";
			this.btnWriteLog.Size = new System.Drawing.Size(152, 23);
			this.btnWriteLog.TabIndex = 2;
			this.btnWriteLog.Text = "Write Event Logs";
			this.btnWriteLog.Click += new System.EventHandler(this.btnWriteLog_Click);
	
 		// 
			// btnClearLog
			// 
			this.btnClearLog.Location = new System.Drawing.Point(32, 106);
			this.btnClearLog.Name = "btnClearLog";
			this.btnClearLog.Size = new System.Drawing.Size(152, 23);
			this.btnClearLog.TabIndex = 3;
			this.btnClearLog.Text = "Clear Logs";
			this.btnClearLog.Click += new System.EventHandler(this.btnClearLog_Click);

			// 
			// btnCreateLog
			// 
			this.btnCreateLog.Location = new System.Drawing.Point(32, 137);
			this.btnCreateLog.Name = "btnCreateLog";
			this.btnCreateLog.Size = new System.Drawing.Size(152, 23);
			this.btnCreateLog.TabIndex = 4;
			this.btnCreateLog.Text = "Create Custom Logs";
			this.btnCreateLog.Click += new System.EventHandler(this.btnCreateLog_Click);

			// 
			// btnDeleteLog
			// 
			this.btnDeleteLog.Location = new System.Drawing.Point(32, 168);
			this.btnDeleteLog.Name = "btnDeleteLog";
			this.btnDeleteLog.Size = new System.Drawing.Size(152, 23);
			this.btnDeleteLog.TabIndex = 5;
			this.btnDeleteLog.Text = "Delete Custom Logs";
			this.btnDeleteLog.Click += new System.EventHandler(this.btnDeleteLog_Click);
			// 
			// btnRecNotice
			// 
			this.btnRecNotice.Location = new System.Drawing.Point(32, 199);
			this.btnRecNotice.Name = "btnRecNotice";
			this.btnRecNotice.Size = new System.Drawing.Size(152, 23);
			this.btnRecNotice.TabIndex = 6;
			this.btnRecNotice.Text = "Receive Event Notifications";
			this.btnRecNotice.Click += new System.EventHandler(this.btnRecNotice_Click);

			// 
			// Form1
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
			this.ClientSize = new System.Drawing.Size(216, 237);
			this.Controls.Add(this.btnRecNotice);
			this.Controls.Add(this.btnDeleteLog);
			this.Controls.Add(this.btnCreateLog);
			this.Controls.Add(this.btnClearLog);
			this.Controls.Add(this.btnWriteLog);
			this.Controls.Add(this.btnReadLog);
			this.Controls.Add(this.btnListLog);
			this.Name = "Form1";
			this.Text = "Form1";
			((System.ComponentModel.ISupportInitialize)(this.eventLog1)).EndInit();
			this.ResumeLayout(false);

		}
		#endregion

		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main() 
		{
			Application.Run(new Form1());
		}

		private void btnListLog_Click(object sender, System.EventArgs e)
		{
			EventLog[] remoteEventLogs; 
			// Gets logs on the local computer, gives remote computer name to get the logs on the remote computer.
			remoteEventLogs = EventLog.GetEventLogs(System.Environment.MachineName);

			Console.WriteLine("Number of logs on computer: " + remoteEventLogs.Length);

			for ( int i=0; i<remoteEventLogs.Length; i++ )
				Console.WriteLine("Log: " + remoteEventLogs[i].Log);
		}

		private void btnReadLog_Click(object sender, System.EventArgs e)
		{

			//logType can be Application, Security, System or any other Custom Log.
			string logType = "Application";
			
			/* In this case the EventLog constructor is passed a string variable for the log name and 
			 * second argument mention the computer name that you want to read the logs from,
			 * and that you have appropriate permissions to*/

			EventLog ev = new EventLog(logType, System.Environment.MachineName);

			int LastLogToShow = ev.Entries.Count;
			if ( LastLogToShow <= 0 )
				Console.WriteLine("No Event Logs in the Log :" + logType);
			// Read the last 2 record in the specified log. 
			int i;
			for ( i = ev.Entries.Count - 1; i>= LastLogToShow - 2; i--)
			{
				EventLogEntry CurrentEntry = ev.Entries[i];
				Console.WriteLine("Event ID : " + CurrentEntry.EventID);
				Console.WriteLine("Entry Type : " + CurrentEntry.EntryType.ToString());
				Console.WriteLine("Message :  " + CurrentEntry.Message + "\n");
			}	

			ev.Close();

			/* Similarly you can loop through all the entries in the log using
			 * the entries collection as shown in the following commented code.
			 * For Each entry In ev.Entries */    
		}

		private void btnWriteLog_Click(object sender, System.EventArgs e)
		{
			/* When writing to an event log, pass the computer name where 
			 * the log resides.  Here the MachineName Property of the Environment class 
			 * is used to determine the name of the local computer.  Assuming that you have 
			 * the appropriate permissions, it is also easy to write to event logs on 
			 * other computers.*/

			//See if the Source exists. 
			if ( ! ( EventLog.SourceExists("MySystemSource", System.Environment.MachineName)))
				EventLog.CreateEventSource("MySystemSource", "System", System.Environment.MachineName);
        
					EventLog ev = new EventLog("System", System.Environment.MachineName, "MySystemSource");
			/* Writing to system log, in the similar way you can write to other 
			 * logs that you have appropriate permissions to write to
			 */
			ev.WriteEntry("Warning is written to system Log", EventLogEntryType.Warning, 10001);
			MessageBox.Show("Warning is written to System Log");
			ev.Close();
		}

		private void btnClearLog_Click(object sender, System.EventArgs e)
		{
			//Create an EventLog instance, and pass log name and MachineName where the log resides.
			EventLog ev = new EventLog("Security", System.Environment.MachineName);
			ev.Clear();
			ev.Close();
		}

		private void btnCreateLog_Click(object sender, System.EventArgs e)
		{
			// Create the source, if it does not already exist.
			if (! (EventLog.SourceExists("MyOldSource", System.Environment.MachineName)))
				// Creating a new log
				EventLog.CreateEventSource("MyOldSource", "MyNewLog", System.Environment.MachineName);
			Console.WriteLine("CreatingEventSource");
		}

		private void btnDeleteLog_Click(object sender, System.EventArgs e)
		{
			string logName = "MyNewLog";

			if ( EventLog.SourceExists("MyOldSource", System.Environment.MachineName))
			{
				logName = EventLog.LogNameFromSourceName("MyOldSource", System.Environment.MachineName);
				EventLog.DeleteEventSource("MyOldSource", System.Environment.MachineName);
				EventLog.Delete(logName, System.Environment.MachineName);
				Console.WriteLine(logName + " deleted.");
			}            
		}

		private void btnRecNotice_Click(object sender, System.EventArgs e)
		{
			// Create the source, if it does not already exist.
			if (EventLog.SourceExists("MySource", System.Environment.MachineName) == false)
			{
				EventLog.CreateEventSource("MySource", "Application", System.Environment.MachineName);
				Console.WriteLine("CreatingEventSource");
			}

			eventLog1.Log = "Application";
			//Enable EnableRaisingEvents to true
			eventLog1.EnableRaisingEvents = true;
			EventLog.WriteEntry("MySource", "EntryWritten event is fired", EventLogEntryType.Information);
		}

		private void eventLog1_EntryWritten(object sender, System.Diagnostics.EntryWrittenEventArgs e)
		{
			if (e.Entry.Source  == "MySource")
				Console.WriteLine("Entry written by my app. Message: " + e.Entry.Message);
		}
	}
}

確認結果

如果要確認結果,請依照下列步驟執行:
  1. 在 Microsoft Visual Studio.NET 或 Microsoft Visual Studio 2005 中,建立一個新 Visual C#.NET 或 Visual C# 2005 Windows 應用程式專案。根據預設值,Form1.vb],即建立。
  2. 用本文程式碼 」 完成程式碼範例 > 一節中所列的程式碼取代中 Form1.vb 的程式碼。
  3. 在 [偵錯] 功能表上按一下 [開始] 執行應用程式]。
  4. 在表單上執行各種動作。
  5. 在 [檢視] 功能表上按一下 伺服器總管 來驗證結果。
  6. 展開 [伺服器],然後再展開 您的電腦名稱
  7. 在 [電腦] 名稱展開 [事件記錄檔]。

    附註無法在 [學術版的 Visual C#.NET 中使用伺服器總管] 的 [伺服器] 節點。在這種情況下您可以使用 Windows 事件檢視器檢視您的應用程式的結果。
  8. 請檢查以確認正確地執行所有工作的伺服器總管]。

?考

如需詳細資訊請造訪下列 Microsoft 網站]:
EventLog 類別
http://msdn2.microsoft.com/en-us/library/system.diagnostics.eventlog(vs.71).aspx

屬性

文章編號: 815314 - 上次校閱: 2007年11月14日 - 版次: 2.6
這篇文章中的資訊適用於:
  • Microsoft Visual C# .NET 2002 Standard Edition
  • Microsoft Visual C# .NET 2003 標準版
  • Microsoft Visual C# 2005 Express Edition
關鍵字:?
kbmt kbeventservice kbnetwork kbmanaged kbprogramming kbhowtomaster kbeventlog kbhowto KB815314 KbMtzh
機器翻譯
重要:本文是以 Microsoft 機器翻譯軟體翻譯而成,而非使用人工翻譯而成。Microsoft 同時提供使用者人工翻譯及機器翻譯兩個版本的文章,讓使用者可以依其使用語言使用知識庫中的所有文章。但是,機器翻譯的文章可能不盡完美。這些文章中也可能出現拼字、語意或文法上的錯誤,就像外國人在使用本國語言時可能發生的錯誤。Microsoft 不為內容的翻譯錯誤或客戶對該內容的使用所產生的任何錯誤或損害負責。Microsoft也同時將不斷地就機器翻譯軟體進行更新。
按一下這裡查看此文章的英文版本:815314
Microsoft及(或)其供應商不就任何在本伺服器上發表的文字資料及其相關圖表資訊的恰當性作任何承諾。所有文字資料及其相關圖表均以「現狀」供應,不負任何擔保責任。Microsoft及(或)其供應商謹此聲明,不負任何對與此資訊有關之擔保責任,包括關於適售性、適用於某一特定用途、權利或不侵權的明示或默示擔保責任。Microsoft及(或)其供應商無論如何不對因或與使用本伺服器上資訊或與資訊的實行有關而引起的契約、過失或其他侵權行為之訴訟中的特別的、間接的、衍生性的損害或任何因使用而喪失所導致的之損害、資料或利潤負任何責任。

提供意見

 

Contact us for more help

Contact us for more help
Connect with Answer Desk for expert help.
Get more support from smallbusiness.support.microsoft.com