如何管理使用 Visual C#.net 或 Visual C# 2005年的事件日志

文章翻译 文章翻译
文章编号: 815314 - 查看本文应用于的产品
为这篇文章的一个 Microsoft Visual Basic.net 版本,请参阅 814564
展开全部 | 关闭全部

本文内容

概要

本分步指南介绍了如何访问和自定义使用 Microsoft.net 框架的 Windows 事件日志。与 EventLog 类与 Windows 事件日志进行交互。使用可以读取从现有日志的 EventLog 类项写入事件日志、 创建或删除事件源、 删除日志,和响应日志条目。本文还介绍如何创建事件源时创建新的日志。

要求

下面的列表概述了建议的硬件、 软件、 网络的基础结构和所需的服务包:
  • Microsoft.net 框架
  • 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 框架中的错误处理

在计算机上查找现有的日志


您可以通过使用共享的方法 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();

写入日志

若要写入事件日志使用 EventLog 类的 WriteEntry 方法中。若要成功写入事件日志,您的应用程序必须具有对它试图写入日志的写访问。您必须具有读取和写入事件日志中的权限有关的详细信息,请访问下面的 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 方法。

注意若要清除事件日志条目您必须在计算机上具有管理员权限的日志 is.
     
//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 类的 删除 方法。多个源可能会写入事件日志。因此,删除一个自定义日志之前,请确保没有其他没有写入该日志的源。
     
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.");
}    

接收事件通知

当特定日志写入条目时,您可以接收事件通知。为此实例的 事件日志 中实现 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. 在 Visual Studio.net 中 Microsoft 或 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 标准版
  • Microsoft Visual C# .NET 2003 标准版
  • Microsoft Visual C# 2005 Express Edition
关键字:?
kbmt kbeventservice kbnetwork kbmanaged kbprogramming kbhowtomaster kbeventlog kbhowto KB815314 KbMtzh
机器翻译
注意:这篇文章是由无人工介入的微软自动的机器翻译软件翻译完成。微软很高兴能同时提供给您由人工翻译的和由机器翻译的文章, 以使您能使用您的语言访问所有的知识库文章。然而由机器翻译的文章并不总是完美的。它可能存在词汇,语法或文法的问题,就像是一个外国人在说中文时总是可能犯这样的错误。虽然我们经常升级机器翻译软件以提高翻译质量,但是我们不保证机器翻译的正确度,也不对由于内容的误译或者客户对它的错误使用所引起的任何直接的, 或间接的可能的问题负责。
点击这里察看该文章的英文版: 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