如何使用 Visual Basic.net 或 Visual Basic 2005 管理事件日志

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

本文内容

概要

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


要求


下面的列表概述了建议的硬件、 软件、 网络的基础结构和所需的服务包:
  • microsoft.net 框架
  • Microsoft Visual Basic.net 或 Microsoft Visual Basic 2005

本文假定您熟悉下列主题:
  • Microsoft Visual Basic.net 或 Microsoft Visual Basic 2005 语法
  • Microsoft Visual Studio.net 或 Microsoft Visual Studio 2005 环境
  • .NET 框架中的错误处理

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


您可以通过使用 EventLog 类的 GetEventLogs 共享方法) 来查找计算机上的现有日志。GetEventLogs 方法搜索在本地计算机上的所有事件日志,然后创建一个包含列表的 EventLog 对象的数组。下面的代码示例检索在本地计算机上的日志列表,然后显示在控制台窗口中的日志的名称:
      Dim remoteEventLogs() As EventLog

      'Gets logs on the local machine, give remote machine name to get the logs on the remote machine
      remoteEventLogs = EventLog.GetEventLogs(System.Environment.MachineName)

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

      'Display the list of event logs
      Dim log As EventLog
      For Each log In remoteEventLogs
         Console.WriteLine("Log: " & log.Log)
      Next log

读和写日志,从本地和远程系统


阅读日志


为事件日志使用 EventLog 类在 项目 的属性。EventLog 类的 项目 属性是在事件日志中的所有项的集合。下面的代码示例演示如何循环访问此集合中,以及如何读取指定的日志中的所有条目:
      ' Log type can be Application, Security, System or any other custom log
      ' Select the log type you want to read
      Dim logtype As String = "Application"

      ' In the constructor of the eventlog, pass the log type and the computer name 
      ' from which you want to read the logs 
      Dim evtLog As New EventLog(logtype, System.Environment.MachineName)

      Dim lastlogtoshow As Integer = evtLog.Entries.Count
      If lastlogtoshow <= 0 Then
         Console.WriteLine("There are no event logs in the log : " & logtype)
         Exit Sub
      End If

      ' Read the last record in the specified log 
      Dim currentEntry As EventLogEntry
      Dim i As Integer
      ' Show Last 2 entries. You can similarly write the log to a file.
      For i = evtLog.Entries.Count - 1 To lastlogtoshow - 2 Step -1
         currentEntry = evtLog.Entries(i)
         Console.WriteLine("Event Id is : " & currentEntry.EventID)
         Console.WriteLine("Entry type is : " & currentEntry.EntryType.ToString())
         Console.WriteLine("Message is :  " & currentEntry.Message & vbCrLf)
      Next
      evtLog.Close()

写入日志


若要写入事件日志使用 EventLog 类的 WriteEntry 方法中。若要成功写入事件日志,请确保您的应用程序已被写入该日志的写访问权限。您必须具有读取和写入事件日志中的权限有关的详细信息,请访问下面的 Microsoft 网站。

安全 Ramification 的事件日志
http://msdn2.microsoft.com/en-us/library/4xz6w79h(vs.71).aspx
向日志中写入项之前,您必须将 EventLog 组件实例上设置 来源 属性。您的组件写入一个条目时, 系统将自动验证您指定的源已注册该组件编写到在事件日志。然后,系统将调用 CreateEventSource 如有必要。若要写入事件日志必须通过计算机名称日志所在的位置。在下面的代码示例的 环境MachineName 属性确定在本地计算机的名称:
      
  ' Check if the source exists 
      If Not EventLog.SourceExists("MySystemSource", System.Environment.MachineName) Then
         EventLog.CreateEventSource("MySystemSource", "System", System.Environment.MachineName)
      End If

      Dim evtLog As New EventLog("System", System.Environment.MachineName, "MySystemSource")

      'writing to system log, in the similar way you can write to other 
      'logs for which you have appropriate permissions to write
      evtLog.WriteEntry("warning is written to system log", EventLogEntryType.Warning, CInt(10001))
      Console.WriteLine("Log written to the system log.")
      evtLog.Close()

清除日志


事件日志满时停止记录新事件信息,或者它将开始覆盖以前的条目。如果将停止事件记录您可以清除现有条目的日志,并允许它再次开始记录事件。若要清除事件日志条目必须对日志所在的计算机的管理员权限。EventLog 组件实例上调用 Clear 方法。

下面的代码示例 domonstrates 如何清除日志:
      ' Create an EventLog instance and pass log name and MachineName on which the log resides
      Dim evtLog As New EventLog("Security", System.Environment.MachineName)
      evtLog.Clear()
      evtLog.Close()

创建和删除自定义日志

创建自定义日志

使用 CreateEventSource 方法来创建您自己的自定义事件处理程序。在创建事件日志之前,请验证您使用的源不尚未存在,然后调用 CreateEventSource 使用 SourceExists 方法。如果试图创建已存在的事件日志将引发一个 System.ArgumentException 错误。

下面的代码示例演示如何创建自定义日志:
      ' Check if the log already exist
      If Not EventLog.SourceExists("MyOldSource", System.Environment.MachineName) Then
         ' Creating a new log
         EventLog.CreateEventSource("MyOldSource", "MyNewLog", System.Environment.MachineName)
         Console.WriteLine("New event log created successfully.")
      End If

删除自定义日志

若要删除事件日志中使用 EventLog 类的 删除 方法。多个源可能会写入事件日志。因此,删除一个自定义日志前,请确保不没有写入该日志的任何其他源。

下面的代码示例演示如何删除一个自定义日志:
      Dim logName As String = "MyNewLog"

      If EventLog.SourceExists("MyOldSource", System.Environment.MachineName) Then
         logName = EventLog.LogNameFromSourceName("MyOldSource", System.Environment.MachineName)
         EventLog.DeleteEventSource("MyOldSource", System.Environment.MachineName)
         EventLog.Delete(logName, System.Environment.MachineName)

         Console.WriteLine(logName & " deleted.")
      End If

接收事件通知

当特定日志写入条目时,您可以接收事件通知。若要执行此操作实现 EntryWritten 事件处理程序为 EventLog 实例。此外,将 EnableRaisingEvents 属性设置为 true

下面的代码示例演示如何接收事件通知:
      If Not EventLog1.SourceExists("MySource", System.Environment.MachineName) Then
         EventLog1.CreateEventSource("MySource", "Application", System.Environment.MachineName)
         Console.WriteLine("CreatingEventSource")
      End If

      'Enable EnableRaisingEvents to true
      EventLog1.Log = "Application"
						EventLog1.EnableRaisingEvents = True
      EventLog1.WriteEntry("MySource", "EntryWritten event is fired", EventLogEntryType.Information)
   End Sub
注意 您只能接收事件通知时项写入本地计算机上。您不能收到有关在远程计算机上写入项的通知。


完成代码列表

Imports System.Diagnostics
Imports System.Security
Imports System.ComponentModel
Imports System.IO

Public Class Form1
   Inherits System.Windows.Forms.Form

#Region " Windows Form Designer generated code "

   Public Sub New()
      MyBase.New()

      'The Windows Form Designer requires this call.
      InitializeComponent()

      'Add any initialization after the InitializeComponent() call

   End Sub

   'Form overrides dispose to clean up the component list.
   Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
      If disposing Then
         If Not (components Is Nothing) Then
            components.Dispose()
         End If
      End If
      MyBase.Dispose(disposing)
   End Sub

   'Required by the Windows Form Designer
   Private components As System.ComponentModel.IContainer

   'NOTE: The Windows Form Designer requires the following procedure
   'It can be modified using the Windows Form Designer.  
   'Do not modify it using the code editor.
   Friend WithEvents EventLog1 As System.Diagnostics.EventLog
   Friend WithEvents btnListLog As System.Windows.Forms.Button
   Friend WithEvents btnReadLog As System.Windows.Forms.Button
   Friend WithEvents btnWriteLog As System.Windows.Forms.Button
   Friend WithEvents btnClearLog As System.Windows.Forms.Button
   Friend WithEvents btnCreateLog As System.Windows.Forms.Button
   Friend WithEvents btnDeleteLog As System.Windows.Forms.Button
   Friend WithEvents btnRecNotice As System.Windows.Forms.Button
   <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
      Me.btnReadLog = New System.Windows.Forms.Button()
      Me.btnWriteLog = New System.Windows.Forms.Button()
      Me.btnClearLog = New System.Windows.Forms.Button()
      Me.btnCreateLog = New System.Windows.Forms.Button()
      Me.btnDeleteLog = New System.Windows.Forms.Button()
      Me.btnRecNotice = New System.Windows.Forms.Button()
      Me.EventLog1 = New System.Diagnostics.EventLog()
      Me.btnListLog = New System.Windows.Forms.Button()
      CType(Me.EventLog1, System.ComponentModel.ISupportInitialize).BeginInit()
      Me.SuspendLayout()
      '
      'btnReadLog
      '
      Me.btnReadLog.Location = New System.Drawing.Point(48, 54)
      Me.btnReadLog.Name = "btnReadLog"
      Me.btnReadLog.Size = New System.Drawing.Size(152, 24)
      Me.btnReadLog.TabIndex = 0
      Me.btnReadLog.Text = "Read Event Logs"
      '
      'btnWriteLog
      '
      Me.btnWriteLog.Location = New System.Drawing.Point(48, 86)
      Me.btnWriteLog.Name = "btnWriteLog"
      Me.btnWriteLog.Size = New System.Drawing.Size(152, 24)
      Me.btnWriteLog.TabIndex = 1
      Me.btnWriteLog.Text = "Write Event Logs"
      '
      'btnClearLog
      '
      Me.btnClearLog.Location = New System.Drawing.Point(48, 118)
      Me.btnClearLog.Name = "btnClearLog"
      Me.btnClearLog.Size = New System.Drawing.Size(152, 24)
      Me.btnClearLog.TabIndex = 2
      Me.btnClearLog.Text = "Clear Logs"
      '
      'btnCreateLog
      '
      Me.btnCreateLog.Location = New System.Drawing.Point(48, 150)
      Me.btnCreateLog.Name = "btnCreateLog"
      Me.btnCreateLog.Size = New System.Drawing.Size(152, 24)
      Me.btnCreateLog.TabIndex = 3
      Me.btnCreateLog.Text = "Create Custom Log"
      '
      'btnDeleteLog
      '
      Me.btnDeleteLog.Location = New System.Drawing.Point(48, 182)
      Me.btnDeleteLog.Name = "btnDeleteLog"
      Me.btnDeleteLog.Size = New System.Drawing.Size(152, 24)
      Me.btnDeleteLog.TabIndex = 4
      Me.btnDeleteLog.Text = "Delete Custom Log"
      '
      'btnRecNotice
      '
      Me.btnRecNotice.Location = New System.Drawing.Point(48, 214)
      Me.btnRecNotice.Name = "btnRecNotice"
      Me.btnRecNotice.Size = New System.Drawing.Size(152, 24)
      Me.btnRecNotice.TabIndex = 5
      Me.btnRecNotice.Text = "Receive Event Notifications"
      '
      'EventLog1
      '
      Me.EventLog1.EnableRaisingEvents = True
      Me.EventLog1.Log = "Application"
      Me.EventLog1.MachineName = System.Environment.MachineName
      Me.EventLog1.SynchronizingObject = Me
      '
      'btnListLog
      '
      Me.btnListLog.Location = New System.Drawing.Point(48, 22)
      Me.btnListLog.Name = "btnListLog"
      Me.btnListLog.Size = New System.Drawing.Size(152, 24)
      Me.btnListLog.TabIndex = 6
      Me.btnListLog.Text = "List Event Logs"
      '
      'Form1
      '
      Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
      Me.ClientSize = New System.Drawing.Size(256, 266)
      Me.Controls.AddRange(New System.Windows.Forms.Control() {Me.btnListLog, Me.btnRecNotice, Me.btnDeleteLog, Me.btnCreateLog, Me.btnClearLog, Me.btnWriteLog, Me.btnReadLog})
      Me.Name = "Form1"
      Me.Text = "Form1"
      CType(Me.EventLog1, System.ComponentModel.ISupportInitialize).EndInit()
      Me.ResumeLayout(False)

   End Sub

#End Region

   Private Sub btnReadLog_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnReadLog.Click

      'logType can be Application, Security, System or any other Custom Log
      Dim logType As String = "Application"


      'In this case the EventLog constructor is passed a string variable for the log name and 
      'second argument mention the computer name from which you want to read the logs 
      'that you have appropriate permissions for
      Dim ev As New EventLog(logType, System.Environment.MachineName)

      Dim LastLogToShow As Integer = ev.Entries.Count
      If LastLogToShow <= 0 Then
         Console.WriteLine("No Event Logs in the Log :" & logType)
         Exit Sub
      End If

      ' read the last 2 records in the specified log 
      Dim i As Integer
      For i = ev.Entries.Count - 1 To LastLogToShow - 2 Step -1
         Dim CurrentEntry As EventLogEntry = ev.Entries(i)

         Console.WriteLine("Event ID : " & CurrentEntry.EventID)
         Console.WriteLine("Entry Type : " & CurrentEntry.EntryType.ToString())
         Console.WriteLine("Message :  " & CurrentEntry.Message & vbCrLf)
      Next

      ev.Close()

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

      ' Next
   End Sub

   Private Sub btnWriteLog_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnWriteLog.Click
      ' When writing to an event log, you must pass the machine name where 
      ' the log resides.  Here the MachineName Property of the Environment class 
      ' is used to determine the name of the local machine.  Assuming you have 
      ' the appropriate permissions, it is also easy to write to event logs on 
      ' other machines.

      'Check if the Source exists 
      If Not EventLog.SourceExists("MySystemSource", System.Environment.MachineName) Then
         EventLog.CreateEventSource("MySystemSource", "System", System.Environment.MachineName)
      End If
      Dim ev As 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, CInt(10001))
      MessageBox.Show("Warning is written to System Log")
      ev.Close()

   End Sub

   Private Sub btnClearLog_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClearLog.Click
      ' Create an EventLog instance and pass the log name and MachineName on which the log resides.
      Dim ev As New EventLog("Security", System.Environment.MachineName)
      ev.Clear()
      ev.Close()
   End Sub

   Private Sub btnCreateLog_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCreateLog.Click
      'Create the source, if it does not already exist.
      If Not EventLog.SourceExists("MyOldSource", System.Environment.MachineName) Then
         'Creating a new log
         EventLog.CreateEventSource("MyOldSource", "MyNewLog", System.Environment.MachineName)
         Console.WriteLine("CreatingEventSource")
      End If
   End Sub

   Private Sub btnDeleteLog_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDeleteLog.Click
      Dim logName As String = "MyNewLog"

      If EventLog.SourceExists("MyOldSource", System.Environment.MachineName) Then
         logName = EventLog.LogNameFromSourceName("MyOldSource", System.Environment.MachineName)
         EventLog.DeleteEventSource("MyOldSource", System.Environment.MachineName)
         EventLog.Delete(logName, System.Environment.MachineName)

         Console.WriteLine(logName & " deleted.")
      End If

   End Sub


   Private Sub btnRecNotice_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRecNotice.Click
      ' Create the source if it does not already exist.
      If Not EventLog1.SourceExists("MySource", System.Environment.MachineName) Then
         EventLog1.CreateEventSource("MySource", "Application", System.Environment.MachineName)
         Console.WriteLine("CreatingEventSource")
      End If

      'Enable EnableRaisingEvents to true
      EventLog1.Log = "Application"
						EventLog1.EnableRaisingEvents = True
      EventLog1.WriteEntry("MySource", "EntryWritten event is fired", EventLogEntryType.Information)
   End Sub

   Private Sub EventLog1_EntryWritten(ByVal sender As Object, ByVal e As System.Diagnostics.EntryWrittenEventArgs) Handles EventLog1.EntryWritten
      If e.Entry.Source = "MySource" Then
         Console.WriteLine("Entry written by my app. Message: " & e.Entry.Message)
      End If
   End Sub

   Private Sub btnListLog_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnListLog.Click
      Dim remoteEventLogs() As EventLog
      'Gets logs on the local machine, give remote machine name to get the logs on the remote machine
      remoteEventLogs = EventLog.GetEventLogs(System.Environment.MachineName)

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

      Dim log As EventLog
      For Each log In remoteEventLogs
         Console.WriteLine("Log: " & log.Log)
      Next log
   End Sub
End Class

注意您必须更改该代码在 Visual Basic 2005 中。默认状态下,Visual Basic 创建项目的两个文件,当您创建一个 Windows 窗体项目时。如果窗体名为 Form1,Form1.vb 和 Form1.Designer.vb,被命名为表示窗体的两个文件。在 Form1.vb 文件中编写代码。Windows 窗体设计器在 Form1.Designer.vb 文件中写入代码。Windows 窗体设计器使用 partial 关键字将 Form1 的实现划分为两个单独的文件。此行为可防止该设计器生成的代码正在与您的代码交错。

有关新的 Visual Basic 2005 语言增强功能的详细信息,请访问下面的 Microsoft 开发人员网络 (MSDN) 的网站:
http://msdn2.microsoft.com/en-us/library/ms379584(vs.80).aspx
有关分部类和 Windows 窗体设计器的详细信息请访问下面的 MSDN 网站:
http://msdn2.microsoft.com/en-us/library/ms171843.aspx

验证结果

要验证您的结果,请按照下列步骤操作:
  1. 通过使用 Visual 基本.net 或 Visual Basic 2005 中创建一个新的 Windows 应用程序。

    默认状态下,创建 Form1.vb
  2. 用这篇文章"完整代码列表"一节中的代码替换中 Form1.vb 代码。
  3. 调试 菜单上单击 $ 开始 以运行该应用程序。
  4. Form1.vb 执行操作。
  5. 若要验证结果,打开服务器资源管理器。若要执行此操作单击在 视图 菜单上的 服务器资源管理器
  6. 展开 服务器 节点,然后展开 您的计算机名称
  7. 您的计算机名称 框中,展开 事件日志

    注意服务器 节点,服务器资源管理器中不可用 Visual Basic.net 学院版。您可以使用 Windows 事件查看器来查看您的应用程序的结果。
  8. 使用服务器资源管理器以验证正确执行此过程中的所有步骤。

参考

有关详细的信息,请访问下面的 Microsoft 网站:

EventLog 类
http://msdn2.microsoft.com/en-us/library/system.diagnostics.eventlog(vs.71).aspx

属性

文章编号: 814564 - 最后修改: 2007年11月14日 - 修订: 2.7
这篇文章中的信息适用于:
  • Microsoft Visual Basic 2005
  • Microsoft Visual Basic .NET 2003 标准版
  • Microsoft Visual .NET 2002 标准版
关键字:?
kbmt kbvs2005swept kbvs2005applies kbeventservice kbnetwork kbmanaged kbprogramming kbeventlog kbhowtomaster KB814564 KbMtzh
机器翻译
注意:这篇文章是由无人工介入的微软自动的机器翻译软件翻译完成。微软很高兴能同时提供给您由人工翻译的和由机器翻译的文章, 以使您能使用您的语言访问所有的知识库文章。然而由机器翻译的文章并不总是完美的。它可能存在词汇,语法或文法的问题,就像是一个外国人在说中文时总是可能犯这样的错误。虽然我们经常升级机器翻译软件以提高翻译质量,但是我们不保证机器翻译的正确度,也不对由于内容的误译或者客户对它的错误使用所引起的任何直接的, 或间接的可能的问题负责。
点击这里察看该文章的英文版: 814564
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