Статьи Королевства Дельфи

       

Просмотрщик событий из журнала событий Windows.


Раздел Подземелье Магов рь,
дата публикации 14 февраля 2002г.

Примечание:
Данный материал не является исчерпывающей статьей по заявленной теме.
товил пояснительный текст к своему проекту.
Основное смотрите в исходных кодах.

В одном из моих проектов мне понабилось просматривать сообщения из журнала событий Windows от одного из источников. Почитав справочник MSDN, я решил, что необходимо сначала все-таки написать выбор всех сообщений из одного из журналов событий, а уж затем отфильтровать нужные мне. Нигде по конференциям и сайтам посвященным Delphi я не нашел ответа на мои вопросы как же там все устроено и решил разобраться сам. Что из этого получилось предоставляю на Ваш строгий суд. Обо всех ошибках и недочетах про сообщать мне по электронной почте .

Что же из себя представляет журнал событий и как с ним работать. Каждый из журналов хранится в системной директории. %SystemRoot%\system32\config\*.evt

Как известно их всего три:

  • Application log - APPEVENT.EVT
  • Security log - SECEVENT.EVT
  • System log - SYSEVENT.EVT
Для чтения записей из журнала используеться функция ReadEventLog предварительно открыв журнал функцией OpenEventLog вот их описание: The OpenEventLog function opens a handle to an event log. HANDLE OpenEventLog( LPCTSTR lpUNCServerName , // server name LPCTSTR lpSourceName // file name ); Параметры: lpUNCServerName [in] Pointer to a null-terminated string that specifies the Universal Naming Convention (UNC) name of the server on which the event log is to be opened. lpSourceName [in] Pointer to a null-terminated string that specifies the name of the logfile that the returned handle will reference. This can be the Application, Security, or System logfile, or a custom registered logfile. If a custom registered logfile name cannot be found, the event logging service opens the Application logfile, however, there will be no associated message or category string file. Return Values:
В случае удачи, функция возвращает handle журнала сообщений. В противном случае будет возвращено Null. Для более подробной информации смотрите GetLastError.
Примечание
Для того, чтобы закрыть журнал событий, используйте функцию CloseEventLog.


The ReadEventLog function reads a whole number of entries from the specified event log. The function can be used to read log entries in chronological or reverse chronological order. BOOL ReadEventLog ( HANDLE hEventLog , // handle to event log DWORD dwReadFlags,, // how to read log DWORD dwRecordOffset, // offset of first record LPVOID lpBuffer, // buffer for read data DWORD nNumberOfBytesToRead,// bytes to read DWORD * pnBytesRead, // number of bytes read DWORD * pnMinNumberOfBytesNeeded // bytes required );

Параметры: hEventLog[in] Handle to the event log to read. This handle is returned by the OpenEventLog function. dwReadFlags [in] Specifies how the read operation is to proceed. This parameter must include one of the following values.
ValueMeaning
EVENTLOG_SEEK_READThe read operation proceeds from the record specified by the dwRecordOffset parameter. This flag cannot be used with EVENTLOG_SEQUENTIAL_READ.
EVENTLOG_SEQUENTIAL_READ The read operation proceeds sequentially from the last call to the ReadEventLog function using this handle. This flag cannot be used with EVENTLOG_SEEK_READ.

If the buffer is large enough, more than one record can be read at the specified seek position; you must specify one of the following flags to indicate the direction for successive read operations.
ValueMeaning
EVENTLOG_FORWARDS_READThe log is read in chronological order. This flag cannot be used with EVENTLOG_BACKWARDS_READ.
EVENTLOG_BACKWARDS_READThe log is read in reverse chronological order. This flag cannot be used with EVENTLOG_FORWARDS_READ.
dwRecordOffset[in] Specifies the log-entry record number at which the read operation should start. This parameter is ignored unless dwReadFlags includes the EVENTLOG_SEEK_READ flag. lpBuffer [out] Pointer to a buffer for the data read from the event log. This parameter cannot be NULL, even if the nNumberOfBytesToRead parameter is zero. The buffer will be filled with an EVENTLOGRECORD structure. nNumberOfBytesToRead[in] Specifies the size, in bytes, of the buffer. This function will read as many whole log entries as will fit in the buffer; the function will not return partial entries, even if there is room in the buffer. pnBytesRead[out] Pointer to a variable that receives the number of bytes read by the function. pnMinNumberOfBytesNeeded[out] Pointer to a variable that receives the number of bytes required for the next log entry. This count is valid only if ReadEventLog returns zero and GetLastError returns ERROR_INSUFFICIENT_BUFFER. Return Values:
В случае удачи, функция возвращает ненулевое значение. В противном случае будет возвращен 0. Для более подробной информации смотрите GetLastError.
Примечание:
When this function returns successfully, the read position in the error log is adjusted by the number of records read. Only a whole number of event log records will be returned.
Note
The configured filename for this source may also be the configured filename for other sources (several sources can exist as subkeys under a single logfile). Therefore, this function may return events that were logged by more than one source.



В принципе уже видно, что для открытия и работы с журналом нам необходимо получить на него указатель передав в функцию в качестве параметра наименование одного из трех журналов. А затем считывать записи в буфер и форматировать их. Как видно буфер который заполняет функция имеет структуру EVENTLOGRECORD.

typedef struct _EVENTLOGRECORD { DWORD Length; DWORD Reserved; DWORD RecordNumber; DWORD TimeGenerated; DWORD TimeWritten; DWORD EventID; WORD EventType; WORD NumStrings; WORD EventCategory; WORD ReservedFlags; DWORD ClosingRecordNumber; DWORD StringOffset; DWORD UserSidLength; DWORD UserSidOffset; DWORD DataLength; DWORD DataOffset; // // Then follow: // // TCHAR SourceName[] // TCHAR Computername[] // SID UserSid // TCHAR Strings[] // BYTE Data[] // CHAR Pad[] // DWORD Length; // } EVENTLOGRECORD, *PEVENTLOGRECORD;

Members
LengthSpecifies the length, in bytes, of this event record. Note that this value is stored at both ends of the entry to ease moving forward or backward through the log. The length includes any pad bytes inserted at the end of the record for DWORD alignment. ReservedReserved RecordNumberContains a record number that can be used with the EVENTLOG_SEEK_READ flag passed in a call to the ReadEventLog function to begin reading at a specified record. TimeGeneratedThe time at which this entry was submitted. This time is measured in the number of seconds elapsed since 00:00:00 January 1, 1970, Universal Coordinated Time. TimeWrittenSpecifies the time at which this entry was received by the service to be written to the logfile. This time is measured in the number of seconds elapsed since 00:00:00 January 1, 1970, Universal Coordinated Time. EventID Specifies the event. This is specific to the source that generated the event log entry, and is used, together with SourceName, to identify a message in a message file that is presented to the user while viewing the log. EventTypeSpecifies the type of event. This member can be one of the following values. For more information, see Event Types. NumStringsSpecifies the number of strings present in the log (at the position indicated by StringOffset). These strings are merged into the message before it is displayed to the user. EventCategorySpecifies a subcategory for this event. This subcategory is source specific. ReservedFlagsReserved ClosingRecordNumberReserved StringOffsetSpecifies the offset of the strings within this event log entry. UserSidLengthSpecifies the length, in bytes, of the UserSid member. This value can be zero if no security identifier was provided. UserSidOffsetSpecifies the offset of the security identifier (SID) within this event record. To obtain the user name for this SID, use the LookAccountSid function. DataLength Specifies the length, in bytes, of the event-specific data (at the position indicated by DataOffset). DataOffsetSpecifies the offset of the event-specific information within this event record. This information could be something specific (a disk driver might log the number of retries, for example), followed by binary information specific to the event being logged and to the source that generated the entry. SourceName Contains the variable-length null-terminated string specifying the name of the source (application, service, driver, subsystem) that generated the entry. This is the name used to retrieve from the registry the name of the file containing the message strings for this source. It is used, together with the event identifier, to get the message string that describes this event. ComputernameContains the variable-length null-terminated string specifying the name of the computer that generated this event. There may also be some pad bytes after this field to ensure that the UserSid is aligned on a DWORD boundary. UserSidSpecifies the security identifier of the active user at the time this event was logged. This member may be empty if the UserSidLength member is zero. Remarks
  • The defined members are followed by the replacement strings for the message identified by the event identifier, the binary information, some pad bytes to make sure the full entry is on a DWORD boundary, and finally the length of the log entry again. Because the strings and the binary information can be of any length, no structure members are defined to reference them.
  • The event identifier together with SourceName and a language identifier identify a message string that describes the event in more detail. The strings are used as replacement strings and are merged into the message string to make a complete message. The message strings are contained in a message file specified in the source entry in the registry. To obtain the appropriate message string from the message file, load the message file with the LoadLibraryEx function and use the FormatMessage function.
  • The binary information is information that is specific to the event. It could be the contents of the processor registers when a device driver got an error, a dump of an invalid packet that was received from the network, a dump of all the structures in a program (when the data area was detected to be corrupt), and so on. This information should be useful to the writer of the device driver or the application in tracking down bugs or unauthorized breaks into the application.
Как видно структура содержит несколько полей, некоторые из которых необходимо тоже форматировать. Для идентификации пользователя используеться функция LookAccountSid. А описание свойства (event) содержит лишь параметры для детального описания сообщения, которое форматируется с помощью функции FormatMessage. Схему форматирования иллюстрирует следующая диаграмма:





Также необходимо учитывать что EventID должны быть получены при наложении маски $0000FFFF (EventID And $0000FFFF). А время форматировать из Unix формата со смещением от нулевого меридиана.

Здесь находиться исходный текст свободно расспространяемой программы: (14K)
Ниже перечислены все функция для работы с журналом событий
  • BackupEventLog
  • ClearEventLog
  • CloseEventLog
  • DeregisterEventSource
  • GetEventLogInformation
  • GetNumberOfEventLogRecords
  • GetOldestEventLogRecord
  • NotifyChangeEventLog
  • OpenBackupEventLog
  • OpenEventLog
  • ReadEventLog
  • RegisterEventSource
  • ReportEvent
В статье использованы материалы из MSDN Library - January 2000, Copyright (c) 1995-2000 Microsoft Corp. All rights reseved.


Cпециально для

ValueMeaning
EVENTLOG_ERROR_TYPEError event
EVENTLOG_WARNING_TYPEWarning event
EVENTLOG_INFORMATION_TYPEInformation event
EVENTLOG_AUDIT_SUCCESSSuccess Audit event
EVENTLOG_AUDIT_FAILUREFailure Audit event

Содержание раздела