如何使用Delphi读取Windows事件日志的内容

时间:2012-10-30 13:17:54

标签: delphi

是否有允许您阅读Windows事件日志的类或函数。这是您打开 eventvwr.msc 时看到的日志。理想情况下,选择一个特定的日志(在我的情况下是 Windows日志下的应用程序日志),并在日期和来源上放置过滤器。

3 个答案:

答案 0 :(得分:6)

您可以使用Win32_NTLogEvent WMI类来读取Windows日志的内容。

试试这个样本

{$APPTYPE CONSOLE}

{$R *.res}

uses
  SysUtils,
  ActiveX,
  ComObj,
  Variants;


procedure  GetLogEvents;
const
  wbemFlagForwardOnly = $00000020;
var
  FSWbemLocator : OLEVariant;
  FWMIService   : OLEVariant;
  FWbemObjectSet: OLEVariant;
  FWbemObject   : OLEVariant;
  oEnum         : IEnumvariant;
  iValue        : LongWord;
begin;
  FSWbemLocator := CreateOleObject('WbemScripting.SWbemLocator');
  FWMIService   := FSWbemLocator.ConnectServer('localhost', 'root\CIMV2', '', '');
  FWbemObjectSet:= FWMIService.ExecQuery('SELECT Category,ComputerName,EventCode,Message,RecordNumber FROM Win32_NTLogEvent  Where Logfile="System"','WQL',wbemFlagForwardOnly);
  oEnum         := IUnknown(FWbemObjectSet._NewEnum) as IEnumVariant;
  while oEnum.Next(1, FWbemObject, iValue) = 0 do
  begin
    Writeln(Format('Category          %s',[String(FWbemObject.Category)]));
    Writeln(Format('Computer Name     %s',[String(FWbemObject.ComputerName)]));
    Writeln(Format('EventCode         %d',[Integer(FWbemObject.EventCode)]));
    Writeln(Format('Message           %s',[String(FWbemObject.Message)]));
    Writeln(Format('RecordNumber      %d',[Integer(FWbemObject.RecordNumber)]));
    FWbemObject:=Unassigned;
  end;
end;

begin
 try
    CoInitialize(nil);
    try
      GetLogEvents;
    finally
      CoUninitialize;
    end;
 except
    on E:EOleException do
        Writeln(Format('EOleException %s %x', [E.Message,E.ErrorCode]));
    on E:Exception do
        Writeln(E.Classname, ':', E.Message);
 end;
 Writeln('Press Enter to exit');
 Readln;
end.

有关更多示例,请尝试此博客条目WMI Tasks using Delphi – Event Logs

答案 1 :(得分:3)

JVCL包含一个名为JvNTEventLog的组件,可以打开和操作Windows事件日志。

答案 2 :(得分:3)

使用ReadEventLog()功能读取事件日志。有关示例,请参阅MSDN:

Querying for Event Information