M Schenkel
M Schenkel

Reputation: 6364

How to Read contents of Windows Event Log Using Delphi

Is there a class or function which allows you to read the Windows event log. This is the log you see when you open eventvwr.msc. And ideally select a specific log (in my case the Applications log under Windows Log), and place filters on date and source.

Upvotes: 2

Views: 6952

Answers (3)

Remy Lebeau
Remy Lebeau

Reputation: 596672

Reading an event log is done with the ReadEventLog() function. See MSDN for an example:

Querying for Event Information

Upvotes: 3

RRUZ
RRUZ

Reputation: 136411

You can use the Win32_NTLogEvent WMI class to read the contents of the Windows Log.

Try this sample

{$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.

For more samples try this blog entry WMI Tasks using Delphi – Event Logs

Upvotes: 7

iMan Biglari
iMan Biglari

Reputation: 4776

JVCL includes a component named JvNTEventLog which can open and manipulate Windows Event Log.

Upvotes: 2

Related Questions