Как анализировать логи windows

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

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

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

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

findstr "Fail" *.log >> fail.txt

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

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

Get-Content -Path 'C:\Program Files\Update Services\LogFiles\SoftwareDistribution.log' | Out-Host -Paging

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

>Get-Content -Path "C:\Windows\WindowsUpdate.log" -Tail 5 -Wait

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

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

Select-String -Path "C:\Windows\System32\LogFiles\Firewall\pfirewall.log" -Pattern 'Drop' | Select-Object -Last 20 | Format-Table Line

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

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

Select-String 'C:\Windows\Cluster\Reports\Cluster.log' -Pattern ' err ' ‑Context 3

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

Get-Content 'C:\Windows\debug\netlogon.log' | Select-Object -First 30 -Skip 45

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

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

Get-WinEvent -ListLog *

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

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

Get-WinEvent -LogName 'System' -MaxEvents 20

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

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

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

Get-WinEvent -FilterHashTable @{LogName='System';ID='1','6013'}

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

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

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

Get-WinEvent -FilterHashtable @{LogName='system'} | Where-Object -FilterScript {($_.Level -eq 2) -or ($_.Level -eq 3)}

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

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

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

  • Get-EventLog.
  • Get-WinEvent.

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

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

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

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

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

SELECT 
 extract_token(text, 0, ' ') as date, 
 extract_token(text, 1, ' ') as time,
 extract_token(text, 2, ' ') as action, 
 extract_token(text, 4, ' ') as src-ip,  
 extract_token(text, 7, ' ') as port 
FROM 'C:\Windows\System32\LogFiles\Firewall\pfirewall.log' 
WHERE action='DROP' AND port='3389'
ORDER BY date,time DESC

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

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

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

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

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

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

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

SELECT
 timegenerated as Date, 
 extract_token(strings, 0, '|') as user,
 extract_token(strings, 2, '|') as sourceip 
FROM '%temp%\test.evtx'
WHERE EventID = 21
ORDER BY Date DESC

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

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

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

SELECT
 TO_LOCALTIME(TO_TIMESTAMP(EXTRACT_PREFIX(TO_STRING([#Fields: date-time]),0,'T'), 'yyyy-MM-dd')) AS Date,
 COUNT(*) AS [Daily Email Traffic] 
FROM 'C:\Program Files\Microsoft\Exchange Server\V15\TransportRoles\Logs\MessageTracking\*.LOG'
WHERE (event-id='RECEIVE') GROUP BY Date ORDER BY Date ASC

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

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

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

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

$LogQuery = New-Object -ComObject "MSUtil.LogQuery"
$InputFormat = New-Object -ComObject "MSUtil.LogQuery.FileSystemInputFormat"
$InputFormat.Recurse = -1
$OutputFormat = New-Object -ComObject "MSUtil.LogQuery.CSVOutputFormat"
$SQLQuery = "SELECT Top 20 Path, Size INTO '%temp%\output.csv' FROM 'C:\*.*' ORDER BY Size DESC"
$LogQuery.ExecuteBatch($SQLQuery, $InputFormat, $OutputFormat)
$CSV = Import-Csv  $env:TEMP'\output.csv'
$CSV | fl 
Remove-Item $env:TEMP'\output.csv'
$LogQuery=$null
$InputFormat=$null
$OutputFormat=$null

Ознакомиться с документацией о работе компонента можно в материале 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.

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

Логи — это ценный инструмент для любого системного администратора или разработчика. Они позволяют отслеживать события, диагностировать ошибки и улучшать работу приложений. Правильное чтение логов помогает быстро выявлять и устранять проблемы, повышая надежность и безопасность систем. В этой статье мы подробно рассмотрим, где хранятся логи в операционных системах Windows и Linux, как их читать и использовать для оптимизации работы.

Что такое логи и зачем они нужны

Лог — это файл, в который система или приложение записывают информацию о событиях, происходящих во время их работы. Журнал сервера (server log) содержит записи о различных аспектах функционирования сервера: от успешных операций до критических ошибок.

Основные причины использовать логи:

  • Диагностика ошибок. Быстрое обнаружение и устранение сбоев.
  • Мониторинг безопасности. Отслеживание несанкционированного доступа и подозрительной активности.
  • Анализ производительности. Оптимизация ресурсов и улучшение отклика системы.
  • Аудит действий. Контроль изменений и действий пользователей.

Где хранятся логи в системах Windows и Linux

Windows

В Windows логи хранятся в «Просмотре событий». Это встроенная утилита, которая собирает и отображает системные и события приложения.

Как открыть «Просмотр событий»:

  1. Нажмите Win + R и введите eventvwr.msc, нажмите Enter.
  2. В открывшемся окне вы увидите разделы:
    • Журналы Windows: включает в себя системные, приложенческие, установочные и другие логи.
    • Журналы приложений и сервисов: специфические логи для отдельных приложений.

Где хранятся файлы логов. Логи Windows сохраняются в файлах с расширением .evtx и находятся по пути:

C:\Windows\System32\winevt\Logs\

Linux

В Linux системные логи обычно находятся в каталоге /var/log/. Этот каталог содержит множество файлов логов для различных системных компонентов и приложений.

Основные файлы логов:

  • /var/log/syslog или /var/log/messages: общесистемные сообщения.
  • /var/log/auth.log: события аутентификации и безопасности.
  • /var/log/kern.log: сообщения ядра системы.
  • /var/log/dmesg: информация о загрузке системы и аппаратных компонентах.
  • /var/log/apache2/: логи веб-сервера Apache.

Где хранятся логи Nginx

Чтение логов и их анализ

Windows

Использование «Просмотра событий»:

  1. В «Просмотре событий» выберите нужный журнал в левой панели.
  2. В центральной панели отобразятся события с деталями: дата и время, источник, уровень (информация, предупреждение, ошибка).
  3. Двойным щелчком по событию откройте подробную информацию.

Поиск и фильтрация:

  • Используйте функцию «Фильтр текущего журнала» для отображения только необходимых событий.
  • Можно фильтровать по ключевым словам, уровням и источникам событий.

Чтение логов в Linux

Командная строка. Просмотр последних строк лога:

tail -n 100 /var/log/syslog

Реальное время обновления:

tail -f /var/log/syslog

Поиск по ключевому слову:

grep "ошибка" /var/log/syslog

Использование специальных приложений:

less: удобный просмотр больших файлов.

less /var/log/syslog

logwatch: утилита для анализа и создания отчетов по логам.

logwatch --detail High --mailto admin@example.com --service all --range today

Примеры использования логов для решения проблем

Пример 1. Устранение ошибки приложения в Linux

Ситуация. Веб-приложение на сервере перестало отвечать.

Действия. Проверить лог веб-сервера:

tail -n 50 /var/log/apache2/error.log
  1. Найти строки с ошибками и обратить внимание на время события.

Если ошибка связана с базой данных, проверить лог базы:

tail -n 50 /var/log/mysql/error.log
  1. По полученной информации принять меры: перезапустить сервис, исправить конфигурацию или обратиться к разработчикам.

Пример 2. Обнаружение несанкционированного доступа в Windows

Ситуация. Подозрение на взлом учётной записи.

Действия:

  1. В «Просмотре событий» открыть «Журналы Windows» Безопасность.
  2. Фильтровать события по ID 4625 (неудачная попытка входа).
  3. Проанализировать время и частоту попыток, IP-адреса.
  4. При необходимости изменить пароли, настроить политику блокировки и уведомить службу безопасности.

Особенности настройки журналов сервера

Настройка логирования в Linux с помощью syslog

syslog — это системный сервис для обработки и хранения логов.

Конфигурационный файл:

  • /etc/rsyslog.conf: основной файл настроек rsyslog.

Настройка уровня логирования:

  • Измените уровень логирования для определенных сервисов.

Например, чтобы записывать только ошибки:

*.err /var/log/errors.log

Удалённое логирование. Настройте отправку логов на удаленный сервер для централизованного хранения.

*.* @logserver.example.com:514

Настройка логирования в приложениях

  • Уровни логирования: DEBUG, INFO, WARNING, ERROR, CRITICAL.
  • Формат логов. Настройте формат записи для удобства чтения и анализа.
  • Ротация логов. Используйте утилиты вроде logrotate для автоматического архивирования и удаления старых логов.

Инструменты для просмотра и анализа логов

Windows

  • Event Log Explorer — расширенная замена стандартному «Просмотру событий», предоставляющая больше возможностей для поиска, фильтрации и анализа журналов Windows.
  • Microsoft Log Parser — утилита для анализа логов с помощью SQL-подобных запросов, позволяющая быстро извлекать нужные данные из большого объёма журналов.

Linux

  • GoAccess — интерактивный инструмент для анализа веб-логов в реальном времени, который отображает статистику по трафику, запросам и ошибкам прямо в терминале или веб-интерфейсе.
  • Graylog и ELK Stack (Elasticsearch, Logstash, Kibana) — системы для централизованного сбора, хранения и визуализации логов, позволяющие анализировать события, отслеживать аномалии и повышать безопасность инфраструктуры.
  • journald — системный журнал в дистрибутивах с systemd, сохраняющий структурированные логи и поддерживающий удобный поиск по параметрам.

Советы по эффективному использованию логов

  • Регулярный мониторинг. Настройте оповещения при появлении критических ошибок.
  • Автоматизация. Используйте скрипты и инструменты для автоматического анализа и отчётов.
  • Безопасность. Ограничьте доступ к логам, так как они могут содержать конфиденциальную информацию.
  • Оптимизация хранения. Следите за размером логов, чтобы избежать заполнения диска.

Заключение

Логи являются неотъемлемой частью системного администрирования и разработки. Понимание того, где хранятся логи и как их читать, позволяет эффективно решать проблемы, улучшать работу приложений и обеспечивать безопасность систем. Используйте предоставленную информацию и инструменты для углубленного анализа и оптимизации вашей инфраструктуры.

Читайте в блоге:

  • Где хранятся логи Nginx
  • Как установить и настроить веб-сервер Nginx на Ubuntu
  • Шесть способов узнать версию Nginx

Журнал событий Windows (Event Log) — это важный инструмент, который позволяет администратору отслеживать ошибки, предупреждения и другие информационные сообщения, которые регистрируются операционной системой, ее компонентами и различными программами. Для просмотра журнала событий Windows можно использовать графическую MMC оснастку Event Viewer (
eventvwr.msc
). В некоторых случаях для поиска информации в журналах событий и их анализа гораздо удобнее использовать PowerShell. В этой статье мы покажем, как получать информацию из журналов событий Windows с помощью командлета Get-WinEvent.

Содержание:

  • Получение логов Windows с помощью Get-WinEvent
  • Get-WinEvent: быстрый поиск в событиях Event Viewer с помощью FilterHashtable
  • Расширенный фильтры событий Get-WinEvent с помощью FilterXml
  • Получить логи Event Viewer с удаленных компьютеров

На данный момент в Windows доступны два командлета для доступа к событиям в Event Log: Get-EventLog и Get-WinEvent. В подавляющем большинстве случаев рекомендуем использовать именно Get-WinEvent, т.к. он более производителен, особенно в сценариях обработки большого количества событий с удаленных компьютеров. Командлет Get-EventLog является устаревшим и использовался для получения логов в более ранних версиях Windows. Кроме того, Get-EventLog не поддерживается в современных версиях PowerShell Core 7.x.

Получение логов Windows с помощью Get-WinEvent

Для использования команды Get-WinEvent нужно запустить PowerShell с правами администратора (при запуске Get-WinEvent от имени пользователя вы не сможете получить доступ к некоторым логам, например, к Security).

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

Get-WinEvent -LogName Application -MaxEvents 20

Чаще всего вам нужно будет получать информацию из журналов System, Application, Security или Setup. Но вы можете указать и другие журналы. Полный список журналов событий в Windows можно получить с помощью команды:

Get-WinEvent -ListLog *

Get-WinEvent командлет PowerShell

Например, чтобы вывести события RDP подключений к компьютеру, нужно указать лог Microsoft-Windows-TerminalServices-RemoteConnectionManager/Operational:

Get-WinEvent -LogName Microsoft-Windows-TerminalServices-RemoteConnectionManager/Operational

Или получить логи SSH подключений к Windows из журнала OpenSSH/Operational:

Get-WinEvent -LogName OpenSSH/Operational

Можно выбрать события сразу из нескольких журналов. Например, чтобы получить информацию о ошибках и предупреждениях из журналов System и Application за последние 24 часа (сутки), можно использовать такой код:

$StartDate = (Get-Date) - (New-TimeSpan -Day 1)
Get-WinEvent Application,System | Where-Object {($_.LevelDisplayName -eq "Error" -or $_.LevelDisplayName -eq "Warning") -and ($_.TimeCreated -ge $StartDate )}

Get-WinEvent командлет для поиска событий в журнале Windows

Чтобы вывести только определенные поля событий, можно использовать Select-Object или Format-Table:

Get-WinEvent -LogName System | Format-Table Machinename, TimeCreated, Id, UserID

Get-WinEvent вывести определенные поля событий

Можно выполнить дополнительные преобразования с полученными данными. Например, в этом примере мы сразу преобразуем имя пользователя в SID:

Get-WinEvent -filterhash @{Logname = 'system'} |
Select-Object @{Name="Computername";Expression = {$_.machinename}},@{Name="UserName";Expression = {$_.UserId.translate([System.Security.Principal.NTAccount]).value}}, TimeCreated

Get-WinEvent: быстрый поиск в событиях Event Viewer с помощью FilterHashtable

Рассмотренный выше способ выбора определенных событий из журналов Event Viewer с помощью Select-Object прост для понимая, но выполняется крайне медленно. Это особенно заметно при выборке большого количества событий. В большинстве случаев для выборки событий нужно использовать фильтрацию на стороне службы Event Viewer с помощью параметра FilterHashtable.

Попробуем сформировать список ошибок и предупреждений за 30 дней с помощью Where-Object и FilterHashtable. Сравнима скорость выполнения этих двух команд PowerShell с помощью Measure-Command:

$StartDate = (Get-Date).AddDays(-30)

Проверим скорость выполнения команды с Where-Object:

(Measure-Command {Get-WinEvent Application,System | Where-Object {($_.LevelDisplayName -eq "Error" -or $_.LevelDisplayName -eq "Warning") -and ($_.TimeCreated -ge $StartDate )}}).TotalMilliseconds

Аналогичная команда с FilterHashtable:

(Measure-Command {Get-WinEvent -FilterHashtable @{LogName = 'System','Application'; Level =2,3; StartTime=$StartDate }})..TotalMilliseconds

В данном примере видно, что команда выборки событий через FilterHashtable выполняется в 30 раз быстрее, чем если бы обычный Where-Object (
2.5
сек vs
76
секунд).

Get-WinEvent FilterHashtable выполняется намного быстрее

Если вам нужно найти события по EventID, используйте следующую команду с FilterHashtable:

Get-WinEvent -FilterHashtable @{logname='System';id=1074}|ft TimeCreated,Id,Message

В параметре FilterHashtable можно использовать фильтры по следующим атрибутам событий:

  • LogName
  • ProviderName
  • Path
  • Keywords (для поиска успешных событий нужно использовать значение 9007199254740992 или для неуспешных попыток 4503599627370496)
  • ID
  • Level (1=FATAL, 2=ERROR, 3=Warning, 4=Information, 5=DEBUG, 6=TRACE, 0=Info)
  • StartTime
  • EndTime
  • UserID (SID пользователя)
  • Data

Пример поиска события за определенный промежуток времени:

Get-WinEvent -FilterHashTable @{LogName='System'; StartTime=(get-date).AddDays(-7); EndTime=(get-date).AddHours(-1); ID=1234}

Если нужно найти определенный текст в описании события, можно использовать такую команду:

Get-WinEvent -FilterHashtable @{logname='System'}|Where {$_.Message -like "*USB*"}

Get-WinEvent поиск текста в событиях

Расширенный фильтры событий Get-WinEvent с помощью FilterXml

Фильтры Get-WinEvent с параметром FilterHashtable являются несколько ограниченными. Если вам нужно использовать для выборки событий сложные запросы с множеством условий, нужно использовать параметр FilterXml, который позволяет сформировать запрос на выбор событий в Event Viewer с помощью XML запроса. Как и FilterHashtable, фильтры FilterXml выполняется на стороне сервера, поэтому результат вы получите довольно быстро.

Например, аналогичный запрос для получения последних ошибок из журнала System за последние 30 дней может выглядеть так:

$xmlQuery = @'
<QueryList>
<Query Id="0" Path="System">
<Select Path="System">*[System[(Level=2 or Level=3) and TimeCreated[timediff(@SystemTime) &lt;= 2592000000]]]</Select>
</Query>
</QueryList>
'@
Get-WinEvent -FilterXML $xmlQuery

Get-WinEvent -FilterXML

Для построения кода сложных XML запросов можно использовать графическую консоль Event Viewer:

  1. Запустите
    eventvwr.msc
    ;
  2. Найдите журнал для которого вы хотите создать и выберите Filter Current Log;
  3. Выберите необходимые параметры запроса в форме. В этом примере я хочу найти события с определенными EventID за последние 7 дней от определенного пользователя;
  4. Чтобы получить код XML запроса для параметра FilterXML, перейдите на вкладку XML и скопируйте полученный код (CTRL+A, CTRL+C);
    XML запрос в Event Viewer

  5. Если нужно, вы можете вручную отредактировать данный запрос.

Для экспорта списка событий в CSV файл нужно использовать командлет Export-CSV:

$Events= Get-WinEvent -FilterXML $xmlQuery
$events| Export-CSV "C:\ps\FilterSYSEvents.csv" -NoTypeInformation -Encoding UTF8

Получить логи Event Viewer с удаленных компьютеров

Для получения события с удаленного компьютер достаточно указать его имя в параметре -ComputerName:

$computer='msk-dc01'
Get-WinEvent -ComputerName $computer -FilterHashtable @{LogName="System"; StartTime=(get-date).AddHours(-24)} |   select Message,Id,TimeCreated

Можно опросить сразу несколько серверов/компьютеров и поискать на них определенные события. Список серверов можно получить из текстового файла:

$servers = Get-Content -Path C:\ps\servers.txt

Или из Active Directory:

$servers = (Get-ADComputer -Filter 'operatingsystem -like "*Windows server*" -and enabled -eq "true"').Name
foreach ($server in $servers) {
Get-WinEvent -ComputerName $server -MaxEvents 5 -FilterHashtable @{
LogName = 'System'; ID= 1234
} | Select-Object -Property ID, MachineName
}

Здесь есть другой пример для поиска событий блокировки учетной записи пользователя на всех контроллерах домена:

$Username = 'a.ivanov'
Get-ADDomainController -fi * | select -exp hostname | % {
$GweParams = @{
‘Computername’ = $_
‘LogName’ = ‘Security’
‘FilterXPath’ = "*[System[EventID=4740] and EventData[Data[@Name='TargetUserName']='$Username']]"
}
$Events = Get-WinEvent @GweParams
$Events | foreach {$_.Computer + " " +$_.Properties[1].value + ' ' + $_.TimeCreated}
}

If you’re using a Windows server and want to know what happened to your machine, Windows logs are an essential resource. Windows logs record various system activities, errors, and other significant events, providing valuable information for troubleshooting, auditing, and ensuring system integrity. Understanding how to access, interpret, and utilise these logs enables efficient, problem solving, enables security measures and ensures the smooth operation of your system.

In this guide, you will learn about Windows event logs, its different categories, how to filter and create Custom Views.

What is a Windows Event Log?

A Windows event log is a file that keeps track of system events and errors, application issues, and security events. Windows Event log can also provide insights into an application’s behavior by tracking its interactions with other processes and services. With the right knowledge of the information stored in these logs, you can easily diagnose and easily resolve issues within your system and applications.

You can access the windows events logs as follows:

Using the Start Menu:

  • Click on the Start button or press the Windows key.
  • Type Event Viewer in the search box and select it from the search results.

Using the Run Dialog:

  • Press Windows + R to open the Run dialog.
  • Type eventvwr and press Enter.

Using the Control Panel:

  • Open the Command Prompt and run as administrator.
  • Type eventvwr and press Enter.

You can see the detailed steps below. Now let’s discuss and understand windows events logs in detail.

Understanding Windows Event Logs categories & Types

There are different Windows logs, each serving a specific purpose in tracking and recording events related to your system, applications, and security. They include:

  • System Events: System events log information is about the core operations of your Windows operating system. System events are essential for maintaining your system’s health and functionality because it records events related to the system’s hardware and software components. Some system events are as follows:
    • Hardware Failures: Logs any issues related to hardware components, such as disc failures or memory errors.
    • Driver Issues: Records events related to the loading, unloading, or malfunctioning of device drivers. This helps in identifying driver-related problems that could affect system stability.
    • System Startups and Shutdowns: Tracks the times when the system starts up or shuts down. This can be useful for understanding system uptime and diagnosing issues related to improper shutdowns or startup failures.
  • Application Events: Data related to software applications running on the system includes application errors, warnings, and informational messages. If you are using a Windows server to run your production-level application, you can use the application errors, warnings, and messages provided here to solve the issue. There are different types of Application events some are as follows:
    • Application Errors: Application errors are events generated by software applications when they encounter issues that prevent them from functioning correctly.
    • Warnings: Logs warnings from applications about potential issues that might not be critical but could lead to problems if not addressed.
    • Informational Messages: Provides general information about application activities, such as successful operations or status updates, helping to understand the normal functioning of applications.
  • Security Events: Security events are logs that capture all security-related activities on your Windows system. They are essential for monitoring, maintaining, and auditing the security of your system. These events help detect unauthorised access attempts, monitor access to sensitive resources, and track changes to system policies. Some security events are as follows:
    • Successful and Failed Login Attempts: Successful and failed login attempts are critical events that are logged by a system to monitor access and ensure security. These logs provide valuable insights into user activity, helping to detect unauthorised access attempts and identify potential security threats.
    • Resource Access: These events log attempts to access protected resources such as files, folders, or system settings. Monitoring these logs ensures that sensitive data is accessed appropriately and helps identify unauthorised access attempts.
    • System Policy Changes: These logs record any changes to system policies, including modifications to user permissions or security settings. This is important for auditing purposes and ensuring compliance with security policies, helping to maintain the integrity and security of the system.
  • Setup Events: Setup events are logs that contain detailed information about the installation and setup processes on your Windows system. These logs are valuable for diagnosing and resolving issues that occur during the installation or configuration of software and system components. Some Setup events are as follows:
    • Installation Processes: Installation processes refer to the series of steps and operations carried out to install software, updates, or system components on a Windows system. It contains log details about software installation, updates, or system components. This helps in diagnosing issues related to incomplete or failed installations.
    • Setup Configurations: Records information about system configurations during the setup process. This can be useful for understanding your system’s initial setup and configuration.
  • Forwarded Events: Forwarded events are logs sent from other computers to a centralised logging server. This is particularly useful in larger environments where centralised log management is needed. They include:
    • Logs from Remote Systems: Collects event logs from multiple systems, allowing for centralised monitoring and management.
    • Centralised Logging Scenarios: Useful for organisations that need to aggregate logs from various systems to a single location for easier analysis and monitoring.

Accessing the Windows Event Viewer

Windows Event Viewer is a Windows application that lets you see your computer’s logs, warnings, and other events. Each application you open generates entries that are recorded in an activity log, which can be viewed from the Event Viewer.

There are several ways to access the Windows Event Viewer. Here are some of them:

  1. Using the Start Menu:

    • Click on the Start button or press the Windows key.
    • Type Event Viewer in the search box.
    Using start menu to open Event viewer

    Using start menu to open Event viewer

    — Select Event Viewer from the search results which will popup something like this.

    Event Viewer main page

    Event Viewer main page

    2. Using the Run Dialog: — Press Windows + R to open the Run dialog. — Type eventvwr and press Enter.

    Windows Run App to open Event Viewer

    Windows Run App to open Event Viewer

    Windows Event viewer landing page

    Windows Event viewer landing page

    3. Using Control Panel: — Open the Command Prompt and run as administrator

    Open CMD as Administrator from start menu

    Open CMD as Administrator from start menu

    — Once open, type eventvwr and press enter, and you will be redirected to Event Viewer page.

    CMD terminal

    CMD terminal

Windows Log Location

Windows event logs are stored in files located in the C:\\Windows\\System32\\winevt\\Logs directory. Each log file corresponds to a specific log category, such as System, Application, or Security. It may differ depending on which version of Windows you are using.

The main event log files are:

  1. Application.evtx: Logs events from applications and programs.
  2. Security.evtx: Logs security events like successful or failed logins.
  3. System.evtx: Logs events related to Windows system components and drivers
Windows Event Viewer logs

Windows Event Viewer logs

You can find many other log files which could be related to system operations & other processes that are happening inside the Windows System. Windows 11uses the .evtx format rather than using the classic EVT format.

Understanding Event Viewer Entries

Event Viewer entries provide detailed information about each logged event. It is like a log book for your Windows system. They record important happenings within the system, including applications, systems, security, failed events, etc. Understanding these entries is key to effective log management.

The key components of an Event Viewer entry are:

  1. Date and Time: When the event occurred.
  2. Source: The application or system component that generated the event.
  3. Event ID: A unique identifier for the event type.
  4. Level: The severity of the event (Information, Warning, Error, Critical).
  5. User: The user account under which the event occurred.
  6. Computer: The name of the computer where the event was logged.
  7. Description: Detailed information about the event.

Each event in the Event Viewer has a severity level, indicating the importance and type of the event:

  • Information (Green Light): These events resemble a green traffic light, signifying smooth sailing. They indicate successful operations or occurrences within your system.
  • Warning (Yellow Light): Treat these entries with caution, like a yellow traffic light. They signal potential issues that warrant attention but might not cause immediate problems.
  • Error (Orange Light): Think of error entries as an orange traffic light; proceed with care. They denote significant problems that could affect system functionality. Imagine an error message indicating a driver failure.
  • Critical (Red Light): Critical entries are akin to a red traffic light; stop and address the situation immediately. They represent severe errors that have caused a major failure. A critical event might report a complete system shutdown or a critical service crashing.
Severity levels for events

Severity levels for events

System Event logs page

System Event logs page

Filtering and Custom Views

Event Viewer allows you to filter events using a variety of parameters, including date, event level, source, and more. Consider the following scenario: your system exhibits weird behaviour, but the Event Viewer is overflowing with hundreds, if not thousands, of entries. Filtering steps and generating custom views can significantly reduce the workload. You may also construct custom views to focus on specific kinds of events:

  1. In the Event Viewer, you’ll see Administrative Events, to create special logs right-click on «Custom Views» and select «Create Custom View.»
Opening Administrative events

Opening Administrative events

Custom View page from Admin Events

Custom View page from Admin Events

1. In the Custom View page, you can see logged drop down, choose a preferred time or it gives you an option to create a custom time to set. 2. On the Event Level choose an appropriate level for your custom view, You can choose among the 5 levels.

Selecting Event Levels

Selecting Event Levels

1. Once done, choose how you want the events to be filtered, By log or By source.

Filtering using: By log

Filtering using: By log

Filtering using: By Source

Filtering using: By Source

Once everything is set up according to your needs, save all events in Custom View as

from the drop-down menu and choose an appropriate location to save the logs. Click on the Save button. (A log file with the extension .evtx will be saved on your device).

Conclusion

This blog provides an understanding how you can use the Windows Event Viewer which is provided by the Windows in default and using it to monitor Windows logs.

  • Main event log files are stored in C:\\Windows\\System32\\winevt\\Logs.
  • Windows logs are crucial for understanding the activities, errors, and significant events on your machine. They provide valuable information for troubleshooting, auditing, and ensuring system integrity.
  • They record a variety of system activities, errors, and other significant events, providing valuable information for troubleshooting, auditing, and ensuring system integrity.
  • We learnt how to setup Filtering and Custom Views to optimise what we see and solve the problems and where it happened.

By grasping the significance of different event types such as System, Application, Security, Setup, and Forwarded Events, and knowing how to filter and export logs, you can effectively manage your Windows system.

FAQ’s

How to view Windows logs?

To view Windows logs, use the built-in Event Viewer:

  1. Press Win + R, type eventvwr, and press Enter.
  2. Navigate through the console tree to find the log you want to view (e.g., Windows Logs > Application).

Where are Microsoft logs?

Microsoft logs, including Windows logs, can be found in the Event Viewer under sections like Application, Security, and System. Log files are also located in the C:\Windows\System32\winevt\Logs directory.

How do I audit Windows logs?

To audit Windows logs:

  1. Open Event Viewer.
  2. Navigate to Security logs under Windows Logs.
  3. Configure auditing policies via the Local Security Policy or Group Policy Management Console.

How do I check my Windows activity log

Check your Windows activity log by viewing the Security logs in Event Viewer. These logs record user logins, logoffs, and other security-related activities.

Which is Windows log key?

The Windows log key, often referred to as the Windows key, is the key on your keyboard with the Windows logo. It is used in various shortcuts to open system tools, including Event Viewer (Win + X > Event Viewer).

Where is the logs folder?

The logs folder is located at C:\Windows\System32\winevt\Logs. This folder contains all the event log files in .evtx format.

Why are Windows logs important?

Windows logs are important because they provide detailed information about system operations, security events, and application behavior, which is crucial for troubleshooting, auditing, and ensuring system integrity.

How to view log files?

View log files using Event Viewer:

  1. Open Event Viewer (Win + R, type eventvwr, press Enter).
  2. Expand the Windows Logs section and select the log you want to view.

Where are login logs?

Login logs are located in the Security logs section of Event Viewer. They record all login attempts, both successful and failed.

What are system logs?

System logs contain information about the core operations of the Windows operating system, including hardware events, driver issues, and system startups and shutdowns. They are found under the System section in Event Viewer.

How do I find Windows log files?

Find Windows log files in the Event Viewer or directly in the C:\Windows\System32\winevt\Logs directory.

How do I view user logs in Windows 10?

View user logs in Windows 10 through the Event Viewer:

  1. Open Event Viewer.
  2. Go to Windows Logs > Security to see logs related to user activities, including logins and logoffs.

How do I view Windows setup logs?

To view Windows setup logs:

  1. Open Event Viewer.
  2. Navigate to Applications and Services Logs > Microsoft > Windows > Setup.

How do I view Windows app logs?

To view Windows application logs:

  1. Open Event Viewer.
  2. Navigate to Windows Logs > Application to see logs related to software applications running on your system.

Was this page helpful?

Logs are constantly recording what is going on on your computer. They can
provide help in tracking what happens with your machine or with troubleshooting.
Logs are kept about both actions by a person or by a running process.

In Windows, logs that are saved contain information about applications and the
operating system itself. Moreover, these logs are structured and human-readable.
For viewing the logs, Windows uses its Windows Event Viewer. This
application displays the event logs and allows the user to search, filter,
export, and analyze background info. In this article, you will learn how to use
the features provided with this program. In addition, this article will also
explore the Event Viewer’s interface and features. Finally, you will also learn
about other application that has their own event viewer built-in, and we will
talk about creating your own repeating tasks.

Prerequisites

  • Windows 10 installed
  • Administration privileges

Step 1 — Accessing Event Viewer

Event viewer is a standard component and can be accessed in several ways. The
easiest way is to type event viewer to the start menu. If you prefer using
command prompt, you can access it by running the eventvwr command.

Event viewer is also accessible through the control panels. Open the control
panels and list them all by viewing them like small or large icons. After that,
select the Administrative Tools and find Event Viewer in the folder.

The application is user-friendly and provides an intuitive interface. The main
screen is divided into three column sections:

  • Navigation page
  • Detail page
  • Action page

You can also create your own section. We will explain how to do that later in
the tutorial.

Step 2 — Understanding Navigation Page

The navigation page, which is by default positioned on the very left, provides
you with an option to choose the event log to view. Five categories can be found
under Windows logs:

  • System — Logs created by the operating system
  • Application— Logged by an application hosted locally
  • Setup — Logs created in the process of installing or changing the Windows
    installation
  • Security — Logs related to logins, privileges, and other similar events
  • Forwarded Events — Events forwarded by other computers

There is also a category for Applications and Services Logs, which contains
logs of the individual applications and Hardware Events. Logs from PowerShell
and other command lines will also be stored there.

Step 3 — Viewing Log Details On Detail Page

When in the default tab, this page displays the Overview and Summary. Select
some item from the previously mentioned navigation page to see more details.
There are several log levels:

  • Information — Successful action
  • Warning — Occurring of an event that might bring problems
  • Error — Occurring of a significant problem
  • Critical — Severe problem occurred

You can also see Audit successes and failures, which are associated with
security events.

Events are listed chronologically, starting with the latest event on the very
top. You can furthermore click on the columns to edit the order and groupings.

You can click on the event to view more detailed information:

You can learn more about an event by double-clicking it:

Here you can see the name of the log, source, and other information about the
log.

The following popup window also has two tabs, General and Details. The
first tab shows more information about the error as described above. The second
tab shows the raw event data. You can switch between Friendly View and XML
View
.

Step 4 — Using Actions Page

The last page located by default on the right side is the Actions page,
which provides you quick access to the features available to you at the moment.
This page is divided into two parts, the first containing actions available for
the selected Navigation page. The second contains actions available to the
selected event itself.

Various options are available:

Filtering Current Log

Allows you to set criteria for events to be displayed on the Details page.

Clearing Log Events

You can choose this option if the list becomes too large. This will delete all
events stored in the current log. You can check the total number of events by
going to the top directory in the navigation page:

Exporting Log Events

You can click on the Save All Events Asor Save All Events in Custom View As
to export all of the selected events into the special event file with the
.EVTX extension.

Step 5 — Creating Custom Views

Event Viewer gives you the option to create a custom view. To do so, select the
Custom Views folder on the Navigation page and click Create Custom View
on the Actions page. You can, for example, create a custom view for all Windows
Azure events with log level error that occurred in the last 12 hours:

After saving, your new view will now show in the Navigation tab.

You can also export your Custom View. Select it in the Navigation Page and find
an option called Export Custom View on the Actions Page. Enter the name for
the new .XML file you are about to create, and it is done.

You can import the custom view to any other Event Viewer by selecting the option
Import Custom View.

Navigating Summary View

The summary view is the first thing you will come in contact with when opening
the Event Viewer. It is at the top of the Navigation panel.

It includes:

  • Overview
  • Summary of Administrative Events — displays data and totals related to the
    Event Viewer for the past week.
  • Recently Viewed Nodes — history of the viewed nodes filtered
    chronologically while the most recent is at the top. You can double-click on
    the node to open the location.
  • Log Summary — this section displays all of the major properties in each
    log file. Double-click to get more details like the events for the viewed log.

Step 6 — Finding Other Application Logs

There are other logs with their event logging:

  • DNS Manager
  • IIS Access
  • Task Scheduler History
  • Failover Cluster Manager
  • Windows Component Service

DNS Manager

If you run Windows Server that is provisioned as a DNS server, the DNS manager
is available. This manager has its list of events. From there, the DNS manager’s
event viewer works in a similar fashion as the one packed with Windows.

IIS Access

The Internet Information Services logs include info about requested URIs and
statuses. These logs are written in the location specified in the IIS Manager.
By default, the location is:

%SystemDrive%\\inetpub\\logs\\LogFiles

Task Scheduler Library

Task scheduler schedules many sorts of background tasks and applications. The
Task Scheduler Library is associated with it, and you can view it directly from
the application:

From the summary view, you can see the overview, task status, and active tasks.
In the task status, you can view all tasks started in some period.
Double-clicking on the task will give you more information.

In the section underneath, you can see all the active tasks that are currently
enabled and have not expired. Then, by double-clicking on the summary info about
the task, which includes the task name, next run time, triggers, and location,
you can again view more information.

Using this feature, you can display details about every single task and modify
it accordingly. The action page also slightly changes, and a new section for the
selected item is viewed. You can run, end, disable, delete or export information
about the task at your will.

From the action panel, you can also create your own task by selecting the option
Create Basic Task... or adding an existing one with Import Task... After
clicking the first opinion, you are presented with a task creator wizard to add
name, description, triggers, action, and finish statement to your custom task.

Failover Cluster Manager

This is a practical built-in application when running your Windows Server. This
service allows servers to work as a cluster. When one server’s hardware fails,
it is automatically detected and replaced by the other server. All network is
then re-routed to the working instance.

This application also has its local Event Viewer. Using this event viewer, you
can discover more in the events of your clusters failing or not working as
expected.

Windows Component Service

Another application is Windows Component Service Manager. It enables us to
configure DCOM applications on Windows. You can view its logs by clicking on the
local Event Viewer:

Conclusion

Windows and applications installed or associated with the operating system keep
records of various events. Understanding and finding these events can help you
if you are a system administrator, running your Windows server, or even just a
regular user.

Now you should know how to explore and use different methods to use these logs
to your advantage. In addition, you now know how to use the task scheduler and
create your own repeating tasks using it.

Jenda leads Growth at Better Stack. For the past 5 years, Jenda has been writing about exciting learnings from working with hundreds of developers across the world. When he’s not spreading the word about the amazing software built at Better Stack, he enjoys traveling, hiking, reading, and playing tennis.

Got an article suggestion?
Let us know

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Windows vista home premium key
  • Как включить упрощенный стиль windows 10 pro
  • Программа для отключения ненужных процессов windows 10
  • Windows soft ru отзывы
  • Digital activation windows 10 github