如何使用 Visual Basic.NET 或 Visual Basic 2005 管理事件日誌

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

在此頁中

結論

本文將逐步告訴您,如何存取和使用 Microsoft.NET Framework 來自訂 Windows 事件記錄檔。您可以與 Windows 事件記錄檔互動,藉由 EventLog 類別。您可以使用 EventLog 類別來執行下列動作:
  • 從現有的記錄檔讀取。
  • 項目寫入事件記錄檔。
  • 建立或刪除事件來源。
  • 刪除記錄檔。
  • 若要記錄項目回應。
本文也說明如何建立事件來源時,建立新的記錄檔。


需求


下列清單列出建議的硬體、 軟體、 網路基礎結構及所需的 Service Pack:
  • 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 Framework 中的錯誤處理

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


請使用 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()

寫入記錄檔


若要編寫事件日誌,使用 的話,WriteEntry 方法的 EventLog 類別。若要順利寫入事件記錄檔,請確定您的應用程式有寫入至記錄檔的寫入權限。如需有關權限,您必須要有讀取和寫入事件記錄檔中的詳細資訊,請造訪下列 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 類別的 Delete 方法刪除事件記錄檔。多個來源可能會將寫入至事件記錄檔。因此,刪除自訂記錄檔之前請確定沒有其他來源寫入該記錄檔。

下列程式碼範例示範如何刪除自訂記錄檔:
      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

接收事件通知

項目寫入特定的記錄檔時,您可以接收事件通知。若要執行此動作實作 EventLog 執行個體 EntryWritten 事件處理常式。而且,將 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 中。當您建立 Windows Form 專案時,預設值,Visual Basic 會建立兩個專案檔案。如果表單名為 Form1,代表表單的兩個檔案被命名 Form1.vb 並 Form1.Designer.vb。Form1.vb 檔案中撰寫程式碼。Windows Form 設計工具將 Form1.Designer.vb 檔案中寫入程式碼。Windows Form 設計工具會使用部分關鍵字,Form1 實作分成兩個獨立的檔案。這種行為可以防止設計工具產生的程式碼正在與您的程式碼位置顛倒。

如需有關新的 Visual Basic 2005 語言加強功能的詳細資訊,請造訪下列 Microsoft 開發 o 人 h 員 ? 工 u 具 ? 網路 (MSDN) 網站]:
http://msdn2.microsoft.com/en-us/library/ms379584(vs.80).aspx
如需有關部分類別和 Windows Form 設計工具的詳細資訊,請造訪下列 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 Standard Edition
  • Microsoft Visual Basic .NET 2002 Standard Edition
關鍵字:?
kbmt kbvs2005swept kbvs2005applies kbeventservice kbnetwork kbmanaged kbprogramming kbeventlog kbhowtomaster KB814564 KbMtzh
機器翻譯
重要:本文是以 Microsoft 機器翻譯軟體翻譯而成,而非使用人工翻譯而成。Microsoft 同時提供使用者人工翻譯及機器翻譯兩個版本的文章,讓使用者可以依其使用語言使用知識庫中的所有文章。但是,機器翻譯的文章可能不盡完美。這些文章中也可能出現拼字、語意或文法上的錯誤,就像外國人在使用本國語言時可能發生的錯誤。Microsoft 不為內容的翻譯錯誤或客戶對該內容的使用所產生的任何錯誤或損害負責。Microsoft也同時將不斷地就機器翻譯軟體進行更新。
按一下這裡查看此文章的英文版本: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