Windows service system event log

Eventlog Key

The event log contains the following standard logs as well as custom logs:

Log Description
Application Contains events logged by applications. For example, a database application might record a file error. The application developer decides which events to record.
Security Contains events such as valid and invalid logon attempts, as well as events related to resource use such as creating, opening, or deleting files or other objects. An administrator can start auditing to record events in the security log.
System Contains events logged by system components, such as the failure of a driver or other system component to load during startup.
CustomLog Contains events logged by applications that create a custom log. Using a custom log enables an application to control the size of the log or attach ACLs for security purposes without affecting other applications.

The event logging service uses the information stored in the Eventlog registry key. The Eventlog key contains several subkeys, called logs. Each log contains information that the event logging service uses to locate resources when an application writes to and reads from the event log.

The structure of the Eventlog key is as follows:

Note that domain controllers record events in the Directory service and File Replication service logs and DNS servers record events in the DNS server.

Each log can contain the following registry values.

Registry value Description
CustomSD Restricts access to the event log. This value is of type REG_SZ. The format used is Security Descriptor Definition Language (SDDL). Construct an ACL that grants one or more of the following rights: Clear (0x0004)
Read (0x0001)
Write (0x0002)
To be a syntactically valid SDDL, the CustomSD value must specify an owner and a group owner (for example, O:BAG:SY), but the owner and group owner are not used. If CustomSD is set to a wrong value, an event is fired in the System event log when the event log service starts, and the event log gets a default security descriptor which is identical to the original CustomSD value for the Application log. SACLs are not supported.
For more information, see Event Logging Security.
Windows Server 2003: SACLs are supported.
Windows XP/2000: This value is not supported.
DisplayNameFile This value is not used. Windows Server 2003 and Windows XP/2000: Name of the file that stores the localized name of the event log. The name stored in this file appears as the log name in Event Viewer. If this entry does not appear in the registry for an event log, Event Viewer displays the name of the registry subkey as the log name. This value is of type REG_EXPAND_SZ. The default value is %SystemRoot%\system32\els.dll.
DisplayNameID This value is not used. Windows Server 2003 and Windows XP/2000: Message identification number of the log name string. This number indicates the message in which the localized display name appears. The message is stored in the file specified by the DisplayNameFile value. This value is of type REG_DWORD.
File Fully qualified path to the file where each event log is stored. This enables Event Viewer and other applications to find the log files. This value is of type REG_SZ or REG_EXPAND_SZ. This value is optional. If the value is not specified, it defaults to %SystemRoot%\system32\winevt\logs\ followed by a file name that is based on the event log registry key name.The specific event log file path should be set using the command line utility wevtutil.exe or by using the EvtSetChannelConfigProperty function with EvtChannelLoggingConfigLogFilePath passed into the PropertyId parameter.
If a specific file is set, make sure that the event log service has full permissions on the file.
This value needs to be a valid file name for a file that is located on a local directory (not a remote computer, not a DOS device, not a floppy, and not a pipe). If the file setting is wrong, an event is fired in the System event log when the event log service starts.
Do not use environment variables, in the path to the file, that cannot be expanded in the context of the event log service.
Windows Server 2003 and Windows XP/2000: This value defaults to %SystemRoot%\system32\config\ followed by a file name that is based on the event log registry key name. If the File setting is set to an invalid value, the log will either not be initialized properly, or all requests will silently go to the default log (Application).
MaxSize Maximum size, in bytes, of the log file. This value is of type REG_DWORD. The value must be set to a multiple of 64K for a System, Application, or Security log. The default value is 1MB.Windows Server 2003 and Windows XP/2000: The value is limited to 0xFFFFFFFF, and the default value is 512K.
PrimaryModule This value is not used.Windows Server 2003 and Windows XP/2000: This value is the name of the subkey that contains the default values for the entries in the subkey for the event source. This value is of type REG_SZ.
Retention This value is of type REG_DWORD. The default value is 0. If this value is 0, the records of events are always overwritten. If this value is 0xFFFFFFFF or any nonzero value, records are never overwritten. When the log file reaches its maximum size, you must clear the log manually; otherwise, new events are discarded. You must also clear the log before you can change its size.Windows Server 2003 and Windows XP/2000: This value is the time interval, in seconds, that records of events are protected from being overwritten. When the age of an event reaches or exceeds this value, it can be overwritten.
Sources This value is not used. Windows Server 2003 and Windows XP/2000: Names of the applications, services, or groups of applications that write events to this log. This value should only be read and not altered. The event log service maintains the list based on each program listed in a subkey under the log. This value is of type REG_MULTI_SZ.
AutoBackupLogFiles This value is of type REG_DWORD, and is used by the event log service to determine whether an event log should be automatically saved. The default value is 0, which disables auto-backup. The service will back up the log file only if the retention value is -1 (0xFFFFFFFF). Other values will be ignored.Windows Server 2003: Retention can be set to -1 (0xFFFFFFFF) or 1 (0x00000001) for AutoBackupLogFiles to work. Other values will be ignored.
RestrictGuestAccess This value is not used. Windows XP/2000: This value is of type REG_DWORD, and the default value is 1. When the value is set to 1, it restricts the Guest and Anonymous account access to the event log, and when this value is 0, it allows Guest account access to the event log.
Isolation Defines the default access permissions for the log. This value is of type REG_SZ. You can specify one of the following values:
  • Application
  • System
  • Custom

The default isolation is Application. The default permissions for Application are (shown using SDDL):
The default permissions for System are (shown using SDDL):
The default permissions for Custom isolation is the same as Application.
Windows Server 2003 and Windows XP/2000: This value is not available.

Each log also contains event sources. For more information, see Event Sources.

Windows Event Log Service not starting or is unavailable

Windows Event Log service maintains a set of event logs that the system, system components, and applications use to record events. The service exposes functions that allow programs to maintain and manage the event logs and perform operations on the logs, such as archiving and clearing. As such, administrators can maintain event logs and perform administrative tasks requiring administrator privileges.

Windows Event Log Service Not Starting or Running

For some unknown reason, if you find you are having difficulty starting the following, it is quite possible that one of the reasons could be that Windows Event Log Service is Not Running.

  • Task Scheduler
  • Windows Event Calendar
  • Messenger Sharing Folders

In such a scenario, you may get error messages like:

Event Log service is unavailable. Verify that the service is running

Windows could not start the Windows Event Log service on Local Computer

First, reboot your system and see if it helps. Sometimes a simple restart helps reinitialize this service. If the Windows Event Log shows as being started, re-start it from Services Manager.

To check if the Windows Event Log service is started or stopped, Run services.msc and hit Enter to open the Services Manager. Here, again right-click on Windows Event Log Service, check up its Properties.

Ensure that the Startup type is set on Automatic and that the services is Started; and that it runs in the Local Service account.

Also ensure in the Recovery tab, all three drop-down boxes, show the option as ‘Restart the Service’, in case of Failure. Reboot if required.

At times the Windows Event Log Service still will not start, and you may instead get the following error message:

System cannot find the file specified

In this case, open the following folder:

This logs folder contains Event Logs in .evtx format and can only be read with the Event Viewer. Give this logs folder Read-Write access rights and see if it helps.

You might also want to do the following.

Open Registry Editor and navigate to the following key:

Double-click ObjectName and ensure that its value is set at NT AUTHORITY\LocalService. If it is not, then change it.

If it still does not help, run the System File Checker and go through its logs.

Вертим логи как хотим ― анализ журналов в системах Windows

Пора поговорить про удобную работу с логами, тем более что в Windows есть масса неочевидных инструментов для этого. Например, Log Parser, который порой просто незаменим.

В статье не будет про серьезные вещи вроде Splunk и ELK (Elasticsearch + Logstash + Kibana). Сфокусируемся на простом и бесплатном.

Журналы и командная строка

До появления PowerShell можно было использовать такие утилиты cmd как find и findstr. Они вполне подходят для простой автоматизации. Например, когда мне понадобилось отлавливать ошибки в обмене 1С 7.7 я использовал в скриптах обмена простую команду:

Она позволяла получить в файле fail.txt все ошибки обмена. Но если было нужно что-то большее, вроде получения информации о предшествующей ошибке, то приходилось создавать монструозные скрипты с циклами for или использовать сторонние утилиты. По счастью, с появлением PowerShell эти проблемы ушли в прошлое.

Основным инструментом для работы с текстовыми журналами является командлет Get-Content, предназначенный для отображения содержимого текстового файла. Например, для вывода журнала сервиса WSUS в консоль можно использовать команду:

Для вывода последних строк журнала существует параметр Tail, который в паре с параметром Wait позволит смотреть за журналом в режиме онлайн. Посмотрим, как идет обновление системы командой:


Смотрим за ходом обновления Windows.

Если же нам нужно отловить в журналах определенные события, то поможет командлет Select-String, который позволяет отобразить только строки, подходящие под маску поиска. Посмотрим на последние блокировки Windows Firewall:


Смотрим, кто пытается пролезть на наш дедик.

При необходимости посмотреть в журнале строки перед и после нужной, можно использовать параметр Context. Например, для вывода трех строк после и трех строк перед ошибкой можно использовать команду:

Оба полезных командлета можно объединить. Например, для вывода строк с 45 по 75 из netlogon.log поможет команда:

Журналы системы ведутся в формате .evtx, и для работы с ними существуют отдельные командлеты. Для работы с классическими журналами («Приложение», «Система», и т.д.) используется Get-Eventlog. Этот командлет удобен, но не позволяет работать с остальными журналами приложений и служб. Для работы с любыми журналами, включая классические, существует более универсальный вариант ― Get-WinEvent. Остановимся на нем подробнее.

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


Вывод доступных журналов и информации о них.

Для просмотра какого-то конкретного журнала нужно лишь добавить его имя. Для примера получим последние 20 записей из журнала System командой:


Последние записи в журнале System.

Для получения определенных событий удобнее всего использовать хэш-таблицы. Подробнее о работе с хэш-таблицами в PowerShell можно прочитать в материале Technet about_Hash_Tables.

Для примера получим все события из журнала System с кодом события 1 и 6013.

В случае если надо получить события определенного типа ― предупреждения или ошибки, ― нужно использовать фильтр по важности (Level). Возможны следующие значения:

  • 0 ― всегда записывать;
  • 1 ― критический;
  • 2 ― ошибка;
  • 3 ― предупреждение;
  • 4 ― информация;
  • 5 ― подробный (Verbose).

Собрать хэш-таблицу с несколькими значениями важности одной командой так просто не получится. Если мы хотим получить ошибки и предупреждения из системного журнала, можно воспользоваться дополнительной фильтрацией при помощи Where-Object:


Ошибки и предупреждения журнала System.

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

Подробнее почитать про работу обоих командлетов для работы с системными журналами можно в документации PowerShell:

PowerShell ― механизм удобный и гибкий, но требует знания синтаксиса и для сложных условий и обработки большого количества файлов потребует написания полноценных скриптов. Но есть вариант обойтись всего-лишь SQL-запросами при помощи замечательного Log Parser.

Работаем с журналами посредством запросов SQL

Утилита Log Parser появилась на свет в начале «нулевых» и с тех пор успела обзавестись официальной графической оболочкой. Тем не менее актуальности своей она не потеряла и до сих пор остается для меня одним из самых любимых инструментов для анализа логов. Загрузить утилиту можно в Центре Загрузок Microsoft, графический интерфейс к ней ― в галерее Technet. О графическом интерфейсе чуть позже, начнем с самой утилиты.

О возможностях Log Parser уже рассказывалось в материале «LogParser — привычный взгляд на непривычные вещи», поэтому я начну с конкретных примеров.

Для начала разберемся с текстовыми файлами ― например, получим список подключений по RDP, заблокированных нашим фаерволом. Для получения такой информации вполне подойдет следующий SQL-запрос:

Посмотрим на результат:


Смотрим журнал Windows Firewall.

Разумеется, с полученной таблицей можно делать все что угодно ― сортировать, группировать. Насколько хватит фантазии и знания SQL.

Log Parser также прекрасно работает с множеством других источников. Например, посмотрим откуда пользователи подключались к нашему серверу по RDP.

Работать будем с журналом TerminalServices-LocalSessionManager\Operational.

Не со всеми журналами Log Parser работает просто так ― к некоторым он не может получить доступ. В нашем случае просто скопируем журнал из %SystemRoot%\System32\Winevt\Logs\Microsoft-Windows-TerminalServices-LocalSessionManager%4Operational.evtx в %temp%\test.evtx.

Данные будем получать таким запросом:


Смотрим, кто и когда подключался к нашему серверу терминалов.

Особенно удобно использовать Log Parser для работы с большим количеством файлов журналов ― например, в IIS или Exchange. Благодаря возможностям SQL можно получать самую разную аналитическую информацию, вплоть до статистики версий IOS и Android, которые подключаются к вашему серверу.

В качестве примера посмотрим статистику количества писем по дням таким запросом:

Если в системе установлены Office Web Components, загрузить которые можно в Центре загрузки Microsoft, то на выходе можно получить красивую диаграмму.


Выполняем запрос и открываем получившуюся картинку…


Любуемся результатом.

Следует отметить, что после установки Log Parser в системе регистрируется COM-компонент MSUtil.LogQuery. Он позволяет делать запросы к движку утилиты не только через вызов LogParser.exe, но и при помощи любого другого привычного языка. В качестве примера приведу простой скрипт PowerShell, который выведет 20 наиболее объемных файлов на диске С.

Ознакомиться с документацией о работе компонента можно в материале Log Parser COM API Overview на портале SystemManager.ru.

Благодаря этой возможности для облегчения работы существует несколько утилит, представляющих из себя графическую оболочку для Log Parser. Платные рассматривать не буду, а вот бесплатную Log Parser Studio покажу.


Интерфейс Log Parser Studio.

Основной особенностью здесь является библиотека, которая позволяет держать все запросы в одном месте, без россыпи по папкам. Также сходу представлено множество готовых примеров, которые помогут разобраться с запросами.

Вторая особенность ― возможность экспорта запроса в скрипт PowerShell.

В качестве примера посмотрим, как будет работать выборка ящиков, отправляющих больше всего писем:


Выборка наиболее активных ящиков.

При этом можно выбрать куда больше типов журналов. Например, в «чистом» Log Parser существуют ограничения по типам входных данных, и отдельного типа для Exchange нет ― нужно самостоятельно вводить описания полей и пропуск заголовков. В Log Parser Studio нужные форматы уже готовы к использованию.

Помимо Log Parser, с логами можно работать и при помощи возможностей MS Excel, которые упоминались в материале «Excel вместо PowerShell». Но максимального удобства можно достичь, подготавливая первичный материал при помощи Log Parser с последующей обработкой его через Power Query в Excel.

Приходилось ли вам использовать какие-либо инструменты для перелопачивания логов? Поделитесь в комментариях.

Читайте также:  Calculate linux установка steam
Оцените статью