Создаем собственный журнал событий в Windows
Как вы знаете, большинство «нормальных» приложений записывают свои события в журнал событий Windows (Application Event Log). Это отличное место для централизованного хранения и просмотра событий приложений, однако зачастую при возникновении необходимости журналировать события от определенного приложения в данном журнале, мы можем столкнуться с тем, что из-за большого количества и чрезмерной подробности событий, работать со стандартным журналом приложений Windows становится очень неудобно. В данном случае было бы удобно создать собственный журнал событий для данного приложения, и для него настраивать различные параметры, такие как размер журнала, фильтры и т.д., а стандартный журнал Application можно использовать как обычно, не засоряя его ненужной информацией. В ОС семейства Windows присутствует функция, позволяющая создать собственный журнал событий.
Сначала создадим новый файл журнала. Сделать это можно при помощи реестра. Запустите редактор реестра regedit и перейдите в ветку:
Щелкните правой кнопкой по узлу Eventlog и создайте новый ключ (New > Key)
Имя ключа в этом случае будет являться и именем нового журнала. По умолчанию новый журнал (файл .evt) создается тут:
Его можно переименовать, изменив строковый параметр в реестре по своему усмотрению.
Далее нужно добавить источники (Sources) событий для нового журнала. Создайте новый ключ типа Multi-String с именем “Sources”, в качестве параметров укажите имена всех приложений, который будут использовать данный журнал (каждое приложение с новой строки).
Затем нужно перенести ассоциации ваших приложений из стандартного журнала Application в ваш новый журнал. Разверните ветку “Application”, находящуюся по адресу:
И скопируйте все ветки, которые относятся к интересуемым Вами приложениям в новый ветку реестра нового журналa:
Т.к. команда скопировать/вставить в редакторе реестра не работает, их можно пересоздать вручную (если их немного), или же можно осуществить перенос при помощи процедуры экспорта/импорта веток реестра с ручным редактирование .reg файла. Убедитесь, что после переноса вы удалили ключи реестра ваших приложений из ветки Application, иначе Windows не поймет, что нужно писать события в новый журнал. В том случае, если вы используете новый источник событий для журнала, нужно будет создать параметр типа DWORD с именем CustomSource и значением равным 1:
В моем примере, я создал собственное приложение .NET 2.0, причем я хочу, чтобы оно записывало события в созданный нами журнал. Для этого я создам новый ключ реестра EventMessageFile и укажу в нем путь к библиотеке журналирования.NET 2.0:
Затем нужно перезагрузить Windows, а после загрузки системы вы увидите новый журнал событий в разделе Event Viewer-а. В том случае, если ваше приложение по какой-либо причине не пишет событий в новый журнал, можно протестировать его работу вручную, откройте командую строку и перейдите в каталог:
В том случае, если вы все сделали правильно должно появиться окно, сообщающее о том, что событие было успешно записан в журнал, либо сообщение об ошибки и причины ее появления.
Update:
Небольшое обновление статьи по письмам читателей:
Вышеприведенная инструкция по созданию собственного журнала ориентирована на серверные ОС семейства Microsoft. Более общий способ, который должен работать в большинстве Windows следующий (отличаются пути в реестре и ключи):
Создаем новый раздел в реестре (имя раздела — имя создаваемого журнала), путь к созданному будет таким:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Eventlog\NewEventLog , в котором нужно создать следующие ключи:
- «AutoBackupLogFiles» — тип DWORD, создавать или нет резервные копии журнала (0 — не создавать)
- «MaxSize» -тип DWORD, максимальны размер журнала в байтах, значение должно быть кратным 64Кб
- «Retention» — тип DWORD, время хранения записей в случае переполнения журнала.
- «File» — тип REG_EXPAND_SZ, строка, в которой содержится путь к логу журнала на жестком диске, например %SystemRoot%\System32\config\NewEventLog.evt)
- «Sources»- тип REG_MULTI_SZ, здесь указан список источников событий, чьи логи должны попадать в этот журнал, каждый источник с новой строки
Windows event log channels
System Requirements
Versions History
- Version 1.30:
- EventLogChannelsView now remembers the last selected channel, and selects the channel automatically in the next time your run it.
- Added ‘Start As Hidden’ option. When this option and ‘Put Icon On Tray’ option are turned on, the main window of EventLogChannelsView will be invisible on start.
- Version 1.28:
- Added ‘Copy Clicked Cell’ option to the right-click context menu, which copies to the clipboard the text of cell that you right-clicked with the mouse.
- Version 1.27:
- Added toolbar button to clear the selected channel.
- Version 1.26:
- Added ‘Provider Guid’ column.
- Version 1.25:
- Added ‘View Channel In FullEventLogView’ option, which allows you to view the events of the selected channel by using the FullEventLogView tool.
- In order to use this feature, you have to put the FullEventLogView.exe file in the same folder of EventLogChannelsView.exe
- You can also use this feature to view the events of the selected channel on a remote computer.
- Be aware that by default the FullEventLogView tool shows only the events in the last 7 days, but you can change it in the ‘Advanced Options’ window (F9).
- Version 1.20:
- Added ‘Select All’ and ‘Deselect All’ to the ‘Column Settings’ window.
- Version 1.19:
- Added ‘Add Header Line To CSV/Tab-Delimited File’ option (Turned on by default).
- Version 1.18:
- Added ‘Save All Items’ option (Shift+Ctrl+S).
- Version 1.17:
- You can now resize the properties window, and the last size/position of this window is saved in the .cfg file.
- Version 1.16:
- Added support for saving as JSON file.
- Version 1.15:
- Added ‘Put Icon On Tray’ option.
- Version 1.13:
- Added option to choose another font (name and size) to display in the main window.
- Version 1.12:
- Added ‘Quick Filter’ feature (View -> Use Quick Filter or Ctrl+Q). When it’s turned on, you can type a string in the text-box added under the toolbar and EventLogChannelsView will instantly filter the event log channels, showing only lines that contain the string you typed.
- Version 1.11:
- Added ‘Set Retention/Backup Mode’ to the context menu.
- Version 1.10:
- You can now set the retention/backup mode of the selected channels (File -> Set Retention/Backup Mode): ‘Overwrite events as needed’ , ‘Archive the log when full’, or ‘Do not overwrite events’.
- Version 1.05:
- Added ‘Hide Channels With 0 Events’ option.
- Version 1.00 — First release.
Start Using EventLogChannelsView
You can select one or more channels and then disable them (F2), enable them (F3), set their maximum file size or clear all events stored in the channel. You can use the ‘Save Selected Items’ option to export the channels list to html/xml/csv/tab-delimited file.
Columns Description
- Channel Name : Name of the event log channel.
- Publisher : Name of the channel publisher.
- Filename : Name of the event log filename ( .evtx and .etl files)
- Full Path : Full path of the event log filename
- Enabled : Displays ‘Yes’ if the event log channel is enabled and ‘No’ if it’s disabled.
- Classic : Displays ‘Yes’ if it’s a classic event log existed in older versions of Windows (Application, System, Security)
- Maximum Size : Maximum size of the event log file in KB.
- File Reached Maximum Size : Displays ‘Yes’ if the file size reached the maximum file size (As displayed in the ‘Maximum Size’ column)
- File Modified Time : Modified time of the event log file.
- File Created Time : Created time of the event log file.
- File Size : Size of the event log file.
- Channel Type : Type of channel — Admin, Analytic, Debug, or Operational.
- Channel Isolation : Isolation mode of the channel — System, Application, or Custom.
- Events Count : Current number of events stored in this event log channel.
- Oldest Record Number : The oldest record number stored in this event log channel.
- AutoBackup Mode : If this value is ‘Yes’, the log will be backed up automatically when it reaches the maximum size.
- Retention Mode : If an event log reaches its maximum size and the Retention Mode is ‘Yes’, existing events are retained and incoming events are discarded. If the Retention Mode is ‘No’, incoming events overwrite the oldest events in the log.
View channel events with FullEventLogView
Command-Line Options
/stext | Save the event log channels into a simple text file. |
/stab | Save the event log channels into a tab-delimited text file. |
/scomma | Save the event log channels into a comma-delimited text file (csv). |
/stabular | Save the event log channels into a tabular text file. |
/shtml | Save the event log channels into HTML file (Horizontal). |
/sverhtml | Save the event log channels into HTML file (Vertical). |
/sxml | Save the event log channels into XML file. |
/sort | This command-line option can be used with other save options for sorting by the desired column. The parameter can specify the column index (0 for the first column, 1 for the second column, and so on) or the name of the column, like «Publisher» and «Channel Name». You can specify the ‘ |
‘ prefix character (e.g: «
Maximum Size») if you want to sort in descending order. You can put multiple /sort in the command-line if you want to sort by multiple columns.
Windows Event Log Error Constants
The following are the error codes that Windows Event Log defines.
ERROR_EVT_INVALID_CHANNEL_PATH
The specified channel path is not valid.
ERROR_EVT_INVALID_QUERY
The specified query is not valid.
ERROR_EVT_PUBLISHER_METADATA_NOT_FOUND
The provider metadata cannot be found in the resource.
ERROR_EVT_EVENT_TEMPLATE_NOT_FOUND
The template for an event definition cannot be found in the resource.
ERROR_EVT_INVALID_PUBLISHER_NAME
The specified provider name is not valid.
ERROR_EVT_INVALID_EVENT_DATA
The event data raised by the provider is not compatible with the event template definition in the provider’s manifest.
ERROR_EVT_CHANNEL_NOT_FOUND
The specified channel cannot be found. Check the channel configuration.
ERROR_EVT_MALFORMED_XML_TEXT
The specified XML text was not well-formed. For more information, call the EvtGetExtendedStatus function.
ERROR_EVT_SUBSCRIPTION_TO_DIRECT_CHANNEL
You cannot subscribe to an Analytic or Debug channel; the events for an Analytic or Debug channel go directly to a log file and cannot be subscribed to.
ERROR_EVT_CONFIGURATION_ERROR
A configuration error occurred.
ERROR_EVT_QUERY_RESULT_STALE
The query result is not valid. This may be due to the log being cleared or rolling over after the query result was created. Release the query result object and reissue the query.
ERROR_EVT_QUERY_RESULT_INVALID_POSITION
The cursor for the query result is not pointing to a valid position.
ERROR_EVT_NON_VALIDATING_MSXML
The registered MSXML parser does not support validation.
ERROR_EVT_FILTER_ALREADYSCOPED
An expression can be followed by a change of scope operation only if the expression evaluates to a node set and is not already part of some other change of scope operation.
ERROR_EVT_FILTER_NOTELTSET
Cannot perform a step operation from a term that does not represent an element set.
ERROR_EVT_FILTER_INVARG
The arguments on the left side of a binary operator must be either attributes, nodes, or variables, and the arguments on the right side must be constants.
ERROR_EVT_FILTER_INVTEST
A step operation must involve either a node test or, in the case of a predicate, an algebraic expression against which to test each node in the node set identified by the preceding node set can be evaluated.
ERROR_EVT_FILTER_INVTYPE
This data type not supported.
ERROR_EVT_FILTER_PARSEERR
A syntax error occurred at the specified position.
ERROR_EVT_FILTER_UNSUPPORTEDOP
This operator is unsupported by this implementation of the filter.
ERROR_EVT_FILTER_UNEXPECTEDTOKEN
The token encountered was unexpected.
ERROR_EVT_INVALID_OPERATION_OVER_ENABLED_DIRECT_CHANNEL
The requested operation cannot be performed over an enabled Analytic or Debug channel. You must disable the channel before performing the requested operation.
ERROR_EVT_INVALID_CHANNEL_PROPERTY_VALUE
The channel property contains a value that is not valid. The value’s type may not be valid, the value may be out of range, or the value cannot be updated or is not supported for this type of channel.
ERROR_EVT_INVALID_PUBLISHER_PROPERTY_VALUE
The provider property contains a value that is not valid. The value’s type may not be valid, the value may be out of range, or the value cannot be updated or is not supported for this type of provider.
ERROR_EVT_CHANNEL_CANNOT_ACTIVATE
The channel failed to activate.
ERROR_EVT_FILTER_TOO_COMPLEX
The XPath expression exceeded supported complexity. Simplify the expression or split it into two or more simple expressions.
ERROR_EVT_MESSAGE_NOT_FOUND
The message resource is present, but the message is not found in the string or message table.
ERROR_EVT_MESSAGE_ID_NOT_FOUND
The message identifier cannot be found.
ERROR_EVT_UNRESOLVED_VALUE_INSERT
The substitution string for the insert index cannot be found.
ERROR_EVT_UNRESOLVED_PARAMETER_INSERT
The description string for parameter reference (%1) cannot be found.
ERROR_EVT_MAX_INSERTS_REACHED
The maximum number of replacements has been reached.
ERROR_EVT_EVENT_DEFINITION_NOT_FOUND
The event definition cannot be found for the event identifier.
ERROR_EVT_MESSAGE_LOCALE_NOT_FOUND
The locale-specific resource for the desired message is not present.
ERROR_EVT_VERSION_TOO_OLD
The resource is too old to be compatible.
ERROR_EVT_VERSION_TOO_NEW
The resource is too new to be compatible.
ERROR_EVT_CANNOT_OPEN_CHANNEL_OF_QUERY
The channel at the specified index of the query cannot be opened.
ERROR_EVT_PUBLISHER_DISABLED
The provider has been disabled and its resources are not available. This can occur when the provider is uninstalled or upgraded.
ERROR_EVT_FILTER_OUT_OF_RANGE
Attempted to create a numeric type that is outside of its valid range.