Обновлено 18.12.2022
Добрый день! Уважаемые читатели и гости IT блога Pyatilistnik.org. В прошлый раз мы с вами рассматривали, как можно установить Internet Information Services. Сегодня я хочу продолжить данную тему и показать вам где хранятся файлы журналов IIS, так как файлы журналов Internet Information Services (IIS) содержат ценную информацию об использовании и состоянии Web приложений. Однако не всегда легко найти, где они находятся, чтобы определить важные аспекты использования приложения, например, когда были сделаны запросы к серверу, кем и другие проблемы пользовательского трафика. Давайте разбираться.
Что такое журнал IIS?
Ведение журнала IIS — это ведение журнала на стороне сервера, которое включено для группы URL-адресов. Журналы IIS имеют фиксированный текстовый формат ASCII и не могут быть настроены. Там можно получить много ценной информации, когда вы ищите источник проблем на вашем веб-сервере. Очень частая ситуация, веб-приложение получает ошибку 5хх, не всегда по коду понятно, в чем причина, что делать, куда смотреть. Лично я такие обращения получаю от разработчиков раз в месяц стабильно.
🗒Расположение журналов IIS
По умолчанию логи IIS после установки располагаются по пути:
%SystemDrive%inetpublogsLogFiles
Данную папку вы можете посмотреть в проводнике Windows. В папке LogFiles вы найдете папки с именами в формате:
- ✅ W3SVC1
- ✅ W3SVC2
- ✅ W3SVC3
Число в конце имени папки соответствует идентификатору сайта. Таким образом, W3SVC2 соответствует идентификатору сайта 2.
Чтобы узнать ID у сайта вам нужно перейти в его дополнительные свойства.
Размер журналов будет зависеть от интенсивности записи в них и можете спокойно достигать по 500 МБ.
Так же вы можете посмотреть ошибки по пути:
%SystemDrive%WindowsSystem32LogFilesHTTPERR
📌Что делать, если вы не можете найти файлы логов IIS?
Администраторы или другой IT-персонал могут легко перенести каталог, в котором они хранятся, в другое расположение. В этом случае очень важно, чтобы пользователи могли быстро находить файлы журналов IIS, чтобы отслеживать работоспособность приложений, устранять неполадки или находить базовую информацию по проблемам кибербезопасности и управления данными.
Чтобы их найти, вы должны запустить оснастку Internet Information Services. Для этого запустите окно «Выполнить» и введите:
Найдите интересующий вас сайт, после чего кликните по иконке «Logging«.
В разделе «Directory» вы увидите, где у вас лежат логи Internet Information Services. При желании вы можете это поменять. Обратите внимание на формат ведения журнала, по умолчанию будет W3C.
W3C используется для централизованного формата файла журнала W3C, для регистрации информации обо всех сайтах на сервере. Этот формат обрабатывается HTTP.sys и представляет собой настраиваемый текстовый формат ASCII, что означает, что вы указываете регистрируемые поля. Укажите поля, которые регистрируются в диалоговом окне «W3C Logging Fields«, щелкнув «Select Fields« на странице Ведение журнала. Поля разделены пробелами, а время записывается в формате всемирного координированного времени (UTC).
По мимо текущих журналов, вы можете еще отслеживать ошибки и предупреждения IIS в логах просмотра событий. Так в журнале «Система» вы можете активировать фильтр с источником WAS. В результате вы получите много ценной информации по поиску проблем на IIS или его пулах.
Еще есть три дополнительных журнала, но они требуют активации, так как по умолчанию они не ведут запись.
- ✅ IIS-CentralCertificateProvider
- ✅ IIS-Configuration
- ✅ IIS-Logging
⚙️Как найти файлы журналов IIS в Azure
Облако Azure:
- Файлы журналов IIS автоматически сохраняются в облачных службах Azure .
- Доступ к файлам журнала с помощью удаленного рабочего стола для подключения к определенному серверу. Там файлы хранятся по пути, похожему на этот: C:Resourcesdirectory{какой-то случайный guid}.{имя приложения}.DiagnosticStoreLogFilesWebW3SVC{случайный номер}
Службы приложений Azure :
- Убедитесь, что ведение журнала веб-сервера включено.
- Настройте ведение журнала веб-сервера для сохранения в файловой системе.
- Файлы расположены в папке: D:homeLogFileshttpRawLogs через консоль KUDU.
📡Как узнать расположение логов IIS с помощью PowerShell
В оболочке PowerShell введите:
Get-Website yoursite | % { Join-Path ($_.logFile.Directory -replace ‘%SystemDrive%’, $env:SystemDrive) «W3SVC$($_.id)» }
или
Get-Website yoursite | % { $_.logFile.Directory, $_.id }
или для всех сайтов
(Get-Website * | % { $_.logFile.Directory});ls $GetIISLogsW3SVC1*
Чтобы получить бонусные баллы, добавьте | iiк первой команде, которую нужно открыть в Проводнике, или | gciк просмотру содержимого папки.
Как удобно изучать логи IIS
Если использовать обычный блокнот для поиска информации в журналах Internet Information Services, то вы увидите, что это неудобно. Для более продуктивной работы я вам советую использовать бесплатную утилиту Log Parser. Я ее использовал уже для удобной работы с файлами формата log.
Где хранятся трассировки IIS
Если вы включите трассировки на сайте, то посмотреть соответствующие журналы можно по пути указанному в дополнительных свойствах сайта. Вам потребуется раздел «Failed Request Tracing«. В моем случае это:
%SystemDrive%inetpublogsFailedReqLogFiles
Как настроить расписание создания логов IIS
Если вы хотите настроить по какому расписанию должны создаваться журналы логов IIS, то вам это нужно сделать через диспетчер. Данная настройка делается, как на уровне всех сайтов, так и на уровне отдельного сайта. Найдите значок «Logging«.
В разделе «Log File Rollover» выберите один из следующих вариантов. Расписание: для создания нового файла журнала на основе одного из следующих значений:
- Ежечасно (Hourly): новый файл журнала создается каждый час.
- Ежедневно (Daily): каждый день создается новый файл журнала.
- Еженедельно (Weekly): каждую неделю создается новый файл журнала.
- Ежемесячно (Monthly): каждый месяц создается новый файл журнала.
- Максимальный размер файла (в байтах) : для создания файла журнала, когда файл достигает определенного размера (в байтах). Минимальный размер файла составляет 1048576 байт. Если для этого атрибута задано значение меньше 1048576 байт, значение по умолчанию неявно принимается равным 1048576 байт.
- Не создавайте новый файл журнала : существует единственный файл журнала, который продолжает расти по мере регистрации информации.
Выберите «Использовать местное время для именования и смены (Use local time for file naming and rollover)» файлов журнала, чтобы указать, что для именования файлов журнала и времени смены файлов журнала используется время локального сервера. Если этот параметр не выбран, используется всемирное координированное время (UTC).
Как выбрать поля W3C для регистрации
Для того, чтобы сделать для себя нужный список полей, которые должны появляться в логах Internet Information Services. Вы должны на уровне сервера или сайта нажать кнопку «Select Fiels» в разделе «Format«
- Дата (дата): дата, когда произошел запрос.
- Время (время): время по всемирному координированному времени (UTC), когда был получен запрос.
- IP-адрес клиента (c-ip): IP-адрес клиента, отправившего запрос.
- Имя пользователя (cs-username): имя аутентифицированного пользователя, который получил доступ к вашему серверу. Анонимные пользователи обозначаются дефисом.
- Имя службы (s-sitename): номер экземпляра сайта, выполнившего запрос.
- Имя сервера (s-computername): имя сервера, на котором была создана запись в файле журнала.
- IP-адрес сервера (s-ip): IP-адрес сервера, на котором была создана запись в файле журнала.
- Порт сервера (s-port): номер порта сервера, настроенный для службы.
- Метод (cs-метод): запрошенное действие, например, метод GET.
- Основа URI (cs-uri-stem): универсальный идентификатор ресурса или цель действия.
- Запрос URI (cs-uri-query): запрос, если таковой имеется, который пытался выполнить клиент. Запрос универсального идентификатора ресурса (URI) необходим только для динамических страниц.
- Состояние протокола (sc-status): код состояния HTTP или FTP.
- Подстатус протокола (sc-substatus): код подстатуса HTTP или FTP.
- Состояние Win32 (sc-win32-status): код состояния Windows.
- Отправлено байтов (sc-bytes): количество байтов, отправленных сервером.
- Получено байтов (cs-bytes): количество байтов, полученных сервером.
- Затраченное время (time-taken): продолжительность действия в миллисекундах.
- Версия протокола (cs-версия): версия протокола, которую использовал клиент.
- Хост (cs-host): имя хоста, если есть.
- Пользовательский агент (cs(UserAgent)): тип браузера, который использовал клиент.
- Cookie (cs(Cookie)): содержимое отправленного или полученного файла cookie, если таковой имеется.
- Referrer (cs(Referrer)): сайт, который последний раз посещал пользователь. Этот сайт предоставил ссылку на текущий сайт.
Как очищать старые логи IIS
Для этого нам опять поможет PowerShell и волшебный скрипт, который сможет удалять журналы в заданном расположении и по разному временному требованию. Сам скрипт искать тут.
Дополнительные ссылки
- https://learn.microsoft.com/en-us/iis/manage/provisioning-and-managing-iis/configure-logging-in-iis
- https://learn.microsoft.com/en-us/iis/manage/provisioning-and-managing-iis/managing-iis-log-file-storage
I’m trying to set up an application from a third party, which requires a supporting website hosted in my local IIS. I’ve created a website exactly as explained in their install guide, but am having some problems, and would like to see what the IIS log has to say. Embarrassingly enough, the problem is I can’t find the log files!
So my question is: Where does IIS7 store logs by default?
asked Jun 21, 2011 at 13:49
0
I think the default place for access logs is
%SystemDrive%inetpublogsLogFiles
Otherwise, check under IIS Manager, select the computer on the left pane, and in the middle pane, go under «Logging» in the IIS area. There you will se the default location for all sites (this is however overridable on all sites)
You could also look into
%SystemDrive%WindowsSystem32LogFilesHTTPERR
Which will contain similar log files that only represents errors.
answered Jun 21, 2011 at 13:51
jishijishi
24k6 gold badges49 silver badges75 bronze badges
7
I believe this is an easier way of knowing where your IIS logs are, rather than just assuming a default location:
Go to your IIS site, e.g. Default, click on it, and you should see «Logging» to the right if logging is enabled:
Open it and you should see the folder right there:
You are welcome!
answered Jan 19, 2016 at 11:51
RafidRafid
18.8k23 gold badges72 silver badges107 bronze badges
2
I’m adding this answer because after researching the web, I ended up at this answer but still didn’t know which subfolder of the IIS logs folder to look in.
If your server has multiple websites, you will need to know the IIS ID for the site. An easy way to get this in IIS is to simply click on the Sites folder in the left panel. The ID for each site is shown in the right panel.
Once you know the ID, let’s call it n, the corresponding logs are in the W3SVCn subfolder of the IIS logs folder. So, if your website ID is 4, say, and the IIS logs are in the default location, then the logs are in this folder:
%SystemDrive%inetpublogsLogFilesW3SVC4
Acknowlegements:
- Answer by @jishi tells where the logs are by default.
- Answer by @Rafid explains how to find actual location (maybe not default).
- Answer by @Bergius gives a programmatic way to find the log folder location for a specific website, taking ID into account, without using IIS.
answered Feb 26, 2016 at 19:08
Joel LeeJoel Lee
3,6361 gold badge18 silver badges21 bronze badges
1
The 100% correct answer for the default location of the log files is…
%SystemDrive%inetpublogsLogFiles
Yes you can enter this into the explorer address bar it’ll work.
To be 100% sure, you need to look at the logging for the web site in IIS.
https://learn.microsoft.com/en-us/iis/get-started/whats-new-in-iis-85/enhanced-logging-for-iis85
i.e.
- Open IIS Manager.
- Select the site or server in the Connections pane,
- Double-click Logging.
- The location of log files for the site can be found within the Directory field
EDIT: As pointed out by Andy in the comments below you need to ensure when installing IIS that you elected to enable HTTP logging, otherwise HTTP logging won’t be available.
answered Nov 5, 2014 at 7:15
MickMick
6,4374 gold badges51 silver badges67 bronze badges
0
A much easier way to do this is using PowerShell, like so:
Get-Website yoursite | % { Join-Path ($_.logFile.Directory -replace '%SystemDrive%', $env:SystemDrive) "W3SVC$($_.id)" }
or simply
Get-Website yoursite | % { $_.logFile.Directory, $_.id }
if you just need the info for yourself and don’t mind parsing the result in your brain :).
For bonus points, append | ii
to the first command to open in Explorer, or | gci
to list the contents of the folder.
answered Jul 3, 2015 at 14:45
BergiusBergius
9496 silver badges14 bronze badges
1
Try the Windows event log, there can be some useful information
answered Jun 21, 2011 at 13:51
Tomas WalekTomas Walek
2,5082 gold badges23 silver badges37 bronze badges
4
Enabling Tracing may be a better alternative to the Windows Event Log. This gave me the information I needed to fix my own WebService.
answered Aug 26, 2014 at 19:25
Preston SPreston S
2,74123 silver badges37 bronze badges
I think the Default place for IIS logging is: c:inetpubwwwrootlogw3svc
Kjartan
18.5k15 gold badges71 silver badges94 bronze badges
answered Jun 17, 2014 at 8:35
honeyhoney
1998 bronze badges
I have found the IIS Log files at the following location.
C:inetpublogsLogFiles
which help to fix my issue.
answered Dec 2, 2017 at 4:47
Hiren ParghiHiren Parghi
1,7951 gold badge20 silver badges30 bronze badges
1
C:inetpublogsLogFiles
Check the identity of the site going to sites and advanced settings
answered May 28, 2019 at 15:20
chandrachandra
1111 gold badge1 silver badge8 bronze badges
The simplest answer is to query like this:
(Get-Website * | % { $_.logFile.Directory});ls $GetIISLogsW3SVC1*
If you have more than one site you will get more than one answer, so you need to query with a ‘foreach’ to get the website name with the directory…
answered Aug 5, 2022 at 16:03
В новой версии Internet Information Services 8.5, представленной в качестве роли веб сервера в Microsoft Windows Server 2012 R2, появилась новая возможность логирования. IIS теперь может писать HTTP-логи в особый журнал трассировки через службу трассировки событий Windows (Event Tracing for Windows — ETW). Благодаря механизму Event Tracing for Windows в IIS 8.5 появилась возможность отслеживать события на веб сервере в реальном времени, что крайне полезно при отладке веб-приложений и поиске неисправностей.
В предыдущих версиях IIS логи веб-сервера записывались в отдельные лог-файлы. Основной недостаток данного механизма – кэширования логов в оперативной памяти. Логи из кэша записываются (сбрасываются) на диск каждую минуты или по достижению объема 64Кб. Это значительно усложняло онлайн-траблшутинг в IIS, т.к. высока вероятность того, что событие, появление которого вы ожидаете, произошло, но информация о нем пока просто не записалась в лог файл, и, соответственно, вы его не сразу не увидите.
Справка. Event Tracing for Windows (ETW) – высокопроизводительная система журналирования, представленная еще в Windows Vista. Системные компоненты и пользовательские приложения при помощи специального API могут отправлять этой системе сообщения о своем состоянии (логи). Система ETW генерирует сравнительно небольшую нагрузку, так, например запись информации о 10000 событий за секунду через службу трассировки займет всего порядка 3% процессорных ресурсов. Система ETW не заменяет обычный журнал событий и служит обычно для непродолжительной по времени диагностики работы приложений или системы.
В этой статье мы покажем, как в IIS 8.5 задействовать службу трассировки событий Windows (ETW) и как проанализировать полученные логи с помощью Microsoft Message Analyzer.
По умолчанию IIS 8.5 записывает логи в обычные тестовые файлы. Чтобы включить логирование через ETW, нужно в панели управления IIS (Internet Information Services Manager), выбрать имя сервера и в правой панели щелкнуть по значку Logging.
Примечание. Опция Logging будет доступна только при установленном компоненте IIS: HTTP Logging (Web Server -> Health and Diagnostics -> HTTP Logging).
В окне настройки параметров журналирования в разделе Log Event Destination выберете метод ведения журнала, переключившись со стандартного Log file only на ETW event only. Обратите внимание, что можно включить ETW и стандартное журналирование IIS одновременно (Both log file and ETW event). Сохраним изменения. Сразу после этого логи веб сервера IIS начнут писаться через службу трассировки событий Windows.
Для просмотра и анализа логов IIS в журналах ETW воспользуемся бесплатным инструментом Microsoft Message Analyzer, который можно скачать с сайта Microsoft по этой ссылке: _http://www.microsoft.com/en-us/download/details.aspx?id=40308
Во время первого запуска Microsoft Message Analyzer спросит, хотите ли вы обновить элементы на стартовом экране. Выберите желаемое действие.
В открывшемся окне Message Analyzer настроим доступ к логам IIS ETW. Для этого щелкните по ссылке Capture/Trace в левой колонке и укажите имя трассировки.
В разделе Trace Scenario Configuration в поле Add Provider введите IIS и из появившегося выпадающего списка выберите Microsoft-Windows-IIS-Logging.
После того, как мы подключились к нужному провайдеру ETW, можно начать просмотр ( и сбор) событий, нажав кнопку Start With.
Собранные данные будут отображены в виде таблицы (если эта опция была указана при запуске).
Чтобы уменьшить количество отображаемой информации, можно применять различные фильтры. Допустим, нам нужно вывести данные, касающиеся только определенного сайта IIS.
Для этого в расширенном описании нужного события щелкнем по полю S_sitename и выберем Add Ssitename To Filter (добавить имя сайта в фильтр).
В окне фильтров появится сгенерированный текст кода фильтра. Если нажать кнопку Apply Filter, в окне журнала останутся только данные, которые относятся к указанному нами сайту.
Аналогичным образом можно добавить фильтр, например, позволяющий оставить в журнале только события с ответом сервера 404 (поле Sc_status).
Итак, в этом небольшом обзоре мы разобрались с новыми возможностями анализа и поиска неисправностей на веб сервере IIS, с помощью журналирования событий веб-сервера через систему ETW. Также мы показали как можно анализировать полученных данных с помощью Microsoft Message Analyzer.
In this article, we will learn about details of IIS Logs i.e. what are IIS logs, what does it contain, data fields from the HTTP requests that are logged into IIS logs, IIS Logs Formats & location of IIS Logs. We will also look at the strategies to manage the IIS log file’s disk usage.
Internet Information Server (IIS) is a web server from Microsoft that gets shipped with Windows Operating System. All the requests made to Web Serves are recorded in IIS Logs.
IIS Provides a logging feature that is efficient, configurable & and flexible logging architecture. You can configure options like IIS log Format, IIS log fields (in W3C format), IIS log location, File Encoding and rollover mechanism for the IIS log files.
Configure IIS Logs
You can configure IIS logs to capture details of all the HTTP requests along with the status that is processed by the sites hosted on that IIS. IIS logs can help you troubleshoot your site.
IIS logs can be configured at the Server or Site level. I personally prefer configuring logging at the Server level as this sets a default logging configuration for all the new sites.
IIS Manager can be used to configure logging. Note that the HTTP Logging feature should be installed (refer to the image below) for logging to be available
Configure or change settings using IIS Manager as shown below
Based on your needs for logging you can configure the following fields:
- One log file per Site or Server, the default value is site & I personally prefer site.
- Log File Format – IIS, NCSA, W3C, or Custom. W3C is a customizable option with different fields so you can log important properties and limit the log size if required.
- Select Fields to be Logged (Only available for file format W3C). The detailed list of Fields is covered in the next section.
- Directory where logs will be saved
- Log Event Destination
- Logfile rollover settings
IIS Log File Format
IIS write a log to the files. There is a fixed format in which the data is written to these log files. As discussed in the previous section the fields to be logged can be configured and also you can select the format for the log file. The W3C Extended format, IIS log format, and NCSA format are all ASCII text formats (unless UTF-8 is enabled for your Web sites).
The W3C IIS log file format allows you to select the fields you want to log for each request. The W3C file is a space-delimited file format and empty fields i.e. fields with no value will be displayed using the hyphen (-). Shown below is the sample of the IIS log file format for one request that is logged using the IIS Logs W3C format.
#Software: Microsoft Internet Information Services 10.0
#Version: 1.0
#Date: 2021-10-18 00:00:18
#Fields: date time s-sitename s-computername s-ip cs-method cs-uri-stem cs-uri-query s-port cs-username c-ip cs(User-Agent) cs(Referer) sc-status sc-substatus sc-win32-status time-taken
2020-02-22 23:59:50 W3SVC2 SERVERNAME1 192.168.0.2 POST /Application/Controller/Action - 80 - 202.124.212.56 Mozilla/5.0+(Linux;+Android+11;+SM-M515F+Build/RP1A.200720.012;+wv)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Version/4.0+Chrome/93.0.4577.62+Mobile+Safari/537.36 - 200 0 0 140
Both the IIS & NCSA log file formats cannot be customized and are fixed ASCII formats. In IIS log file format the items are comma-separated. In NSCA fields are separated by space and empty fields are represented by a hyphen (-). The IIS log file format records more information than the NCSA log file format.
There is a tool provided by Microsoft Log Parser using which you can read the data from the IIS log files. Using this tool you will be able to run SQL-like queries against the log file and produce the desired report on screen or in a file.
List of IIS W3C Log Fields
Here is the complete list of fields that are available for logging in to the IIS logging module under log file format W3C.
- Date (date): date of request.
- Time (time): time of the request in Coordinated Universal Time (UTC).
- Client IP Address (c-ip): the client IP address that made the request.
- User Name (cs-username): the name of the authenticated user who made the request. A hyphen indicates an anonymous user.
- Service Name (s-sitename): the site service name and instance number that handled the request.
- Server Name (s-computername): the name of the server on which the request was made.
- Server IP Address (s-ip): the IP address of the server on which the request was made.
- Server Port (s-port): the server port number that is configured for the service.
- Method (cs-method): the requested action, for example, a GET method.
- URI Stem (cs-uri-stem): the URI, or target, of the action.
- URI Query (cs-uri-query): the query, if any, that the client was trying to perform. A URI query is necessary only for dynamic pages.
- Protocol Status (sc-status): the HTTP request status code.
- Protocol Substatus (sc-substatus): the HTTP request substatus error code.
- Win32 Status (sc-win32-status): the Windows status code.
- Bytes Sent (sc-bytes): the number of bytes that the server sent to the client.
- Bytes Received (cs-bytes): the number of bytes that the server received from the client.
- Time Taken (time-taken): the time the request took to complete (in milliseconds).
- Protocol Version (cs-version): the HTTP protocol version that the client used.
- Host (cs-host): the hostname, if any.
- User Agent (cs(UserAgent)): the browser type that the client uses for requests.
- Cookie (cs(Cookie)): the content of the cookie sent or received.
- Referrer (cs(Referrer)): the site that the user last visited. This site provided a link to the current site.
The default location for IIS Log files is %SystemDrive%inetpublogsLogFiles. But one can even change this default location and log to a different directory.
To verify or change the IIS logs file location follow the below steps
1. Start IIS Manager (Version 8.5) either from Start, =>run “intetmgr” or from Control Panel=>Administrative Tools=>Internet Information Services (IIS) Manager
2. In IIS Manager from Connections Tree on the left Panel select the site for which the Logs directory needs to be configured. From Feature View in the middle double click on Icon Logging
On the Logging screen under Log File=>Directory, you can find the configured location for IIS Log Files. Alternatively, you can click on the action “View Log Files” to navigate directly to the logs folder in Windows Explorer.
Manage IIS Log File Storage
IIS will generate logs and if traffic to your application is higher then it will generate huge log files on a daily basis. I have even seen log files with sizes greater than 1 GB on a daily basis. These huge log files will occupy your disk space and fill it sooner than you realize. So you need to monitor the disk space used & also apply some strategies for cleaning or moving the log files generated for your application.
There are multiple options using which you can manage the disk space available for writing logs to the disk. Below are some of the strategies which you can adapt
- You can delete older log files i.e. you can decide that you need log files for how many days or months and if you decide to keep IIS log files for 30 days then accordingly you can delete the log files that are older than 30 days. So at any given moment, you will have 30 log files on your storage disk.
- If you have a requirement that you cannot delete the older log files and need to maintain all the log files then in that case you can move the older log files to another disk or remote system. This way you will avoid the log disk full problem with the main log disk where logs are being written and move the log files to another server either in the same domain or a different domain.
- You can even decide to use the Windows folder compression option for the log disk. Normally IIS Log files compress to about 2% of their original size. You can right-click on the log folder and click properties. In the properties window, you can select advance and then tick the check box for compressed contents to save disk space on the advanced screen and click Apply/Ok.
For deleting old log files and moving log files to different disks you can automate the task by writing a script that can be scheduled to run on a daily basis.
There is also an IIS Log Cleaner tool available to perform a cleanup action on the older log files. It is a simple tool to enforce a log retention policy for IIS. This tool deletes the log files older than the maximum age that you set and will run in the background once every hour. This is a third-party tool so doesn’t come with IIS. When you run this tool first time it will generate the settings.txt file in the same folder from where the tool was executed. This settings.txt file contains the configuration like the log file folder to be cleaned and the maximum age at which a log file is deleted.
Analyze IIS Logs
IIS logs can provide the following types of insights
- Performance – How fast or slow are our requests?
- User Behaviour – What a user is doing on the application?
- Business Details – Which request has a high or less volume?
- Operational – Total data sent or received by the server
IIS logs data can be used to improve the performance of the applications by checking time taken by critical business requests, analyzing user activities to improve navigation & minimizing errors by checking the HTTP status codes and sub-status codes.
You can use one of the various available tools to analyze IIS logs. One of the tools is WebLog Expert which provides a complete analysis report from IIS Logs.
You can also manually analyze IIS Logs using the free tool provided by Microsoft i.e. Log Parser. Log Parser is a command-line tool used to query IIS Logs. In fact, as per Microsoft, Log Parser is universal query access to text-based data such as log files, XML, CSV & Windows Event Logs. Log Parser supports a variety of output formats.
The log parser can be downloaded from this link. Installation is pretty simple. Alternatively, the Log Parser Studio that is built on top of the log parser can also be used for the analysis of IIS Logs. Log Parser Studio is a graphical user interface-based tool that comes with many predefined queries that can be used for analysis.
Here are a couple of sample log parser queries to read IIS Log files data
//Total requests count by IP Address
logparser -i:w3c "select c-ip, count(c-ip) as requestcount from [LogFileName] where cs-uri-stem like ‘/popuplarpost.aspx%’ group by c-ip order by count(c-ip) desc"
Sample value for [LogFileName] - 'C:IISLogsWeb*.log'
//Total of each request by date - output getting logged into csv
logparser -i:w3c "select date, cs-uri-stem, count(*) as TotalRequestCount INTO 'C:IISReportsTotalRequestsPerDay.csv' from 'C:IISLogsWeb*.log' group by date, cs-uri-stem ORDER BY count(*) desc"
Real-time monitoring of IIS logs to detect security issues or slow-moving requests is also possible and can help big time in keeping applications up & running.
Reference: https://docs.microsoft.com/en-us/iis/manage/provisioning-and-managing-iis/configure-logging-in-iis
You can also check my other Article explaining how to analyze ASP.NET application issues – https://procodeguide.com/programming/analyze-aspnet-application-issues/
Download Article
Download Article
This wikiHow teaches you how to find a list of all the saved log files for IIS (Internet Information Services) events on your computer, and view an event’s recorded logs, using Windows.
-
1
Click the search button on your computer’s taskbar. This button looks like a white magnifier icon next to the Start menu in the lower-left corner of your screen.
- If you’re using Cortana, this button will look like a white circle.
-
2
Enter Event Viewer into the search. This will list all the matching results as you type.
Advertisement
-
3
Click Event Viewer in the search results. Your Windows system’s stock Event Viewer app should show up at the top of the results. Clicking will open it in a new window.
-
4
Click the
icon next to the Windows Logs folder. You can find this folder on the Event Viewer’s left sidebar. It will expand log categories below the folder name.
-
5
Click Application below Windows Logs on the sidebar. This will list all the application logs on the right-hand side of the Event Viewer window.
-
6
Click the Source heading at the top of the list. The Event Viewer is organized by columns like Level, Date and Time, Source, and Event ID at the top. Click Source here to put the list in alphabetical order according to log source.
- You will see «IIS» in the Source column for all IIS events.
-
7
Double-click an IIS event log on the list. When you find the event you want to check, double-click on it to see the recorded log.
Advertisement
Ask a Question
200 characters left
Include your email address to get a message when this question is answered.
Submit
Advertisement
Thanks for submitting a tip for review!
About This Article
Article SummaryX
1. Click the search or Cortana on the bottom-left.
2. Search and open Event Viewer.
3. Expand Windows Logs on the sidebar.
4. Click Application.
5. Click the Source tab.
6. Find and double-click an IIS event to view the log.
Did this summary help you?
Thanks to all authors for creating a page that has been read 52,876 times.