方法 :イベントのクエリ
指定したクエリ条件に一致するイベントのグループを照会して、イベント ログに格納されたイベントをフィルタ処理できます。クエリは、イベント プロパティに基づいてイベントをフィルタ処理します。たとえば、所定の期間内に発生した、あるイベント ログのレベル 2 のイベントをすべて照会したり、識別子が 105 に一致するイベントをすべて照会したりできます。
例
説明
次のコード例では、System.Diagnostics.Eventing.Reader クラスを使用して、アプリケーション イベント ログのレベル 2 のイベントをすべて照会します。説明、イベント ID、およびイベント発行者の名称が、クエリから返されたイベントごとに表示されます。このコード例では、アクティブなイベント ログ、外部のイベント ログ、およびリモート コンピュータのイベントを照会する方法を示します。このコード例の各メソッドでは、イベントを照会するための一連の手順に従います。
イベントのフィルタ処理に使用するクエリ文字列、および照会対象のイベント ログの名前または場所を指定して、EventLogQuery クラスのインスタンスを作成します。外部のイベント ログを照会するには、ログ ファイル (.evtx) へのパスを指定します。イベント ログ名の検索方法の詳細については、「方法 :イベント ログのプロパティを構成し、読み取る」のコード例を参照してください。または、イベント ビューア ツールでイベント ログを検索してください。イベント クエリ文字列を作成する方法の詳細については、「イベント クエリとイベント XML」を参照してください。
(オプション) リモート コンピュータのイベントを照会するには、Session プロパティを EventLogSession クラスのインスタンスに設定します。次に、リモート コンピュータに接続するために使用するリモート コンピュータ名、ドメイン、およびユーザー名とパスワードを指定します。
手順 1. で作成した EventLogQuery インスタンスを指定して、EventLogReader クラスのインスタンスを作成します。
クエリの結果を取得するには、ReadEvent メソッドから返された EventRecord インスタンスを使用します。返された各インスタンスには、クエリ結果のイベントのイベント情報が保持されています。イベント インスタンスからイベント情報を読み取る方法の詳細については、「方法 :イベント情報のアクセスと読み取り」を参照してください。
コード
Imports System
Imports System.Diagnostics.Eventing.Reader
Imports System.Security
Public Class EventQueryExample
Public Overloads Shared Function Main( _
ByVal args() As String) As Integer
Dim ex As New EventQueryExample()
ex.QueryActiveLog()
ex.QueryExternalFile()
ex.QueryRemoteComputer()
End Function
Public Sub QueryActiveLog()
Dim queryString As String = "*[System/Level=2]" ' XPATH Query
Dim eventsQuery As New EventLogQuery("Application", PathType.LogName, queryString)
Dim logReader As New EventLogReader(eventsQuery)
Dim eventInstance As EventRecord = logReader.ReadEvent()
While Not eventInstance Is Nothing
' Display event info
Console.WriteLine("-----------------------------------------------------")
Console.WriteLine("Event ID: {0}", eventInstance.Id)
Console.WriteLine("Publisher: {0}", eventInstance.ProviderName)
Console.WriteLine("Description: {0}", eventInstance.FormatDescription())
eventInstance = logReader.ReadEvent()
End While
End Sub
Public Sub QueryExternalFile()
Dim queryString As String = "*[System/Level=2]" ' XPATH Query
Dim eventLogLocation As String = "C:\MyEvents.evtx"
Dim eventsQuery As New EventLogQuery(eventLogLocation, PathType.FilePath, queryString)
Try
Dim logReader As New EventLogReader(eventsQuery)
Dim eventInstance As EventRecord = logReader.ReadEvent()
While Not eventInstance Is Nothing
' Display event info
Console.WriteLine("-----------------------------------------------------")
Console.WriteLine("Event ID: {0}", eventInstance.Id)
Console.WriteLine("Publisher: {0}", eventInstance.ProviderName)
Console.WriteLine("Description: {0}", eventInstance.FormatDescription())
eventInstance = logReader.ReadEvent()
End While
Catch e As EventLogNotFoundException
Console.WriteLine("Could not find the external log to query! " & e.Message)
Return
End Try
End Sub
Public Sub QueryRemoteComputer()
Dim queryString As String = "*[System/Level=2]" ' XPATH Query
Dim pw As SecureString = GetPassword()
Dim session As EventLogSession = New EventLogSession( _
"RemoteComputerName", _
"Domain", _
"Username", _
pw, _
SessionAuthentication.Default)
pw.Dispose()
' Query the Application log on the remote computer.
Dim query As EventLogQuery = New EventLogQuery( _
"Application", PathType.LogName, queryString)
query.Session = session
Try
Dim reader As New EventLogReader(query)
Dim instance As EventRecord = reader.ReadEvent()
While Not instance Is Nothing
Console.WriteLine("------------------------------")
Console.WriteLine("Event ID: {0}", instance.Id)
Console.WriteLine("Description: {0}", instance.FormatDescription())
instance = reader.ReadEvent()
End While
Catch e As EventLogException
Console.WriteLine("Could not query the remote computer! " & e.Message)
Return
End Try
End Sub
' <summary>
' Read a password from the console into a SecureString
' </summary>
' <returns>Password stored in a secure string</returns>
Public Function GetPassword() As SecureString
Dim password As New SecureString()
Console.WriteLine("Enter password: ")
' get the first character of the password
Dim nextKey As ConsoleKeyInfo = Console.ReadKey(True)
While nextKey.Key <> ConsoleKey.Enter
If nextKey.Key = ConsoleKey.Backspace Then
If password.Length > 0 Then
password.RemoveAt(password.Length - 1)
' erase the last * as well
Console.Write(nextKey.KeyChar)
Console.Write(" ")
Console.Write(nextKey.KeyChar)
End If
Else
password.AppendChar(nextKey.KeyChar)
Console.Write("*")
End If
nextKey = Console.ReadKey(True)
End While
Console.WriteLine()
' lock the password down
password.MakeReadOnly()
Return password
End Function
End Class
using System;
using System.Diagnostics.Eventing.Reader;
using System.Security;
namespace EventQuery
{
class EventQueryExample
{
static void Main(string[] args)
{
EventQueryExample ex = new EventQueryExample();
ex.QueryActiveLog();
ex.QueryExternalFile();
ex.QueryRemoteComputer();
}
public void QueryActiveLog()
{
string queryString = "*[System/Level=2]"; // XPATH Query
EventLogQuery eventsQuery = new EventLogQuery("Application", PathType.LogName, queryString);
EventLogReader logReader = new EventLogReader(eventsQuery);
for (EventRecord eventInstance = logReader.ReadEvent();
null != eventInstance; eventInstance = logReader.ReadEvent())
{
// Display event info
Console.WriteLine("-----------------------------------------------------");
Console.WriteLine("Event ID: {0}", eventInstance.Id);
Console.WriteLine("Publisher: {0}", eventInstance.ProviderName);
Console.WriteLine("Description: {0}", eventInstance.FormatDescription());
}
}
public void QueryExternalFile()
{
string queryString = "*[System/Level=2]"; // XPATH Query
string eventLogLocation = @"C:\MyEvents.evtx";
EventLogQuery eventsQuery = new EventLogQuery(eventLogLocation, PathType.FilePath, queryString);
try
{
EventLogReader logReader = new EventLogReader(eventsQuery);
for (EventRecord eventInstance = logReader.ReadEvent();
null != eventInstance; eventInstance = logReader.ReadEvent())
{
// Display event info
Console.WriteLine("-----------------------------------------------------");
Console.WriteLine("Event ID: {0}", eventInstance.Id);
Console.WriteLine("Publisher: {0}", eventInstance.ProviderName);
Console.WriteLine("Description: {0}", eventInstance.FormatDescription());
}
}
catch (EventLogNotFoundException e)
{
Console.WriteLine("Could not find the external log to query! " + e.Message);
return;
}
}
public void QueryRemoteComputer()
{
string queryString = "*[System/Level=2]"; // XPATH Query
SecureString pw = GetPassword();
EventLogSession session = new EventLogSession(
"RemoteComputerName", // Remote Computer
"Domain", // Domain
"Username", // Username
pw,
SessionAuthentication.Default);
pw.Dispose();
// Query the Application log on the remote computer.
EventLogQuery query = new EventLogQuery("Application", PathType.LogName, queryString);
query.Session = session;
try
{
EventLogReader reader = new EventLogReader(query);
for (EventRecord instance = reader.ReadEvent(); instance != null; instance = reader.ReadEvent())
{
Console.WriteLine("------------------------------");
Console.WriteLine("Event ID: {0}", instance.Id);
Console.WriteLine("Description: {0}", instance.FormatDescription());
}
}
catch (EventLogException e)
{
Console.WriteLine("Could not query the remote computer! " + e.Message);
return;
}
}
/// <summary>
/// Read a password from the console into a SecureString
/// </summary>
/// <returns>Password stored in a secure string</returns>
public static SecureString GetPassword()
{
SecureString password = new SecureString();
Console.WriteLine("Enter password: ");
// get the first character of the password
ConsoleKeyInfo nextKey = Console.ReadKey(true);
while (nextKey.Key != ConsoleKey.Enter)
{
if (nextKey.Key == ConsoleKey.Backspace)
{
if (password.Length > 0)
{
password.RemoveAt(password.Length - 1);
// erase the last * as well
Console.Write(nextKey.KeyChar);
Console.Write(" ");
Console.Write(nextKey.KeyChar);
}
}
else
{
password.AppendChar(nextKey.KeyChar);
Console.Write("*");
}
nextKey = Console.ReadKey(true);
}
Console.WriteLine();
// lock the password down
password.MakeReadOnly();
return password;
}
}
}
コードのコンパイル
このコード例では、System.dll、System.Security.dll、および System.Core.dll ファイルへの参照が必要です。
関連項目
概念
イベント ログのシナリオ
方法 :イベント ログのイベントをサブスクライブする
このトピックに関するコメントを Microsoft に送信する。
Copyright © 2007 by Microsoft Corporation.All rights reserved.