Обновлено 18.12.2022
Добрый день! Уважаемые читатели и гости IT блога Pyatilistnik.org. В прошлый раз мы с вами рассматривали, как можно установить Internet Information Services. Сегодня я хочу продолжить данную тему и показать вам где хранятся файлы журналов IIS, так как файлы журналов Internet Information Services (IIS) содержат ценную информацию об использовании и состоянии Web приложений. Однако не всегда легко найти, где они находятся, чтобы определить важные аспекты использования приложения, например, когда были сделаны запросы к серверу, кем и другие проблемы пользовательского трафика. Давайте разбираться.
Что такое журнал IIS?
Ведение журнала IIS — это ведение журнала на стороне сервера, которое включено для группы URL-адресов. Журналы IIS имеют фиксированный текстовый формат ASCII и не могут быть настроены. Там можно получить много ценной информации, когда вы ищите источник проблем на вашем веб-сервере. Очень частая ситуация, веб-приложение получает ошибку 5хх, не всегда по коду понятно, в чем причина, что делать, куда смотреть. Лично я такие обращения получаю от разработчиков раз в месяц стабильно.
🗒Расположение журналов IIS
По умолчанию логи IIS после установки располагаются по пути:
%SystemDrive%\inetpub\logs\LogFiles
Данную папку вы можете посмотреть в проводнике Windows. В папке LogFiles вы найдете папки с именами в формате:
- ✅ W3SVC1
- ✅ W3SVC2
- ✅ W3SVC3
Число в конце имени папки соответствует идентификатору сайта. Таким образом, W3SVC2 соответствует идентификатору сайта 2.
Чтобы узнать ID у сайта вам нужно перейти в его дополнительные свойства.
Размер журналов будет зависеть от интенсивности записи в них и можете спокойно достигать по 500 МБ.
Так же вы можете посмотреть ошибки по пути:
%SystemDrive%\Windows\System32\LogFiles\HTTPERR
📌Что делать, если вы не можете найти файлы логов 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:\Resources\directory\{какой-то случайный guid}.{имя приложения}.DiagnosticStore\LogFiles\Web\W3SVC{случайный номер}
Службы приложений Azure :
- Убедитесь, что ведение журнала веб-сервера включено.
- Настройте ведение журнала веб-сервера для сохранения в файловой системе.
- Файлы расположены в папке: D:\home\LogFiles\http\RawLogs через консоль 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 $GetIISLogs\W3SVC1\*
Чтобы получить бонусные баллы, добавьте | iiк первой команде, которую нужно открыть в Проводнике, или | gciк просмотру содержимого папки.
Как удобно изучать логи IIS
Если использовать обычный блокнот для поиска информации в журналах Internet Information Services, то вы увидите, что это неудобно. Для более продуктивной работы я вам советую использовать бесплатную утилиту Log Parser. Я ее использовал уже для удобной работы с файлами формата log.
Где хранятся трассировки IIS
Если вы включите трассировки на сайте, то посмотреть соответствующие журналы можно по пути указанному в дополнительных свойствах сайта. Вам потребуется раздел «Failed Request Tracing«. В моем случае это:
%SystemDrive%\inetpub\logs\FailedReqLogFiles
Как настроить расписание создания логов 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
In many cases, when troubleshooting web applications hosted in IIS, we start by collecting the basics for investigation:
- The configuration of IIS and underlying HTTP.SYS, of Asp.Net and of the application, and system info.
- The logs and traces from IIS, HTTP.SYS, Windows Events. If we’re lucky, we have FREBs, Failed Request Traces.
- Problem description, to help us figure out how and where to focus during investigation.
The script at http://linqto.me/Grabber or the app at http://aka.ms/LogCatcher should help automate the steps below. And the article at http://linqto.me/IisTS describes why we collect these files.
Start collecting
Many of the files are only accessible to the Administrators on the investigated machine.
So open an administrative command-line console if you’re going to use the commands below. Then…
First, create a folder where all collected files will be placed:
MKDIR C:\MsLogs
C:
CD \MsLogs
Collect HTTP.SYS configuration
netsh http show cacheparam > C:\MsLogs\netsh_http_show_cacheparam.txt
netsh http show cachestate > C:\MsLogs\netsh_http_show_cachestate.txt
netsh http show iplisten > C:\MsLogs\netsh_http_show_iplisten.txt
netsh http show servicestate > C:\MsLogs\netsh_http_show_servicestate.txt
netsh http show setting > C:\MsLogs\netsh_http_show_setting.txt
netsh http show sslcert > C:\MsLogs\netsh_http_show_sslcert.txt
netsh http show timeout > C:\MsLogs\netsh_http_show_timeout.txt
netsh http show urlacl > C:\MsLogs\netsh_http_show_urlacl.txt
Master IIS configuration — applicationHost.config
Default location is:
C:\Windows\System32\inetsrv\config\
Note: It’s better if you can send the whole folder C:\Windows\System32\inetsrv\config\.
Example:
XCOPY %systemroot%\System32\inetsrv\config\*.* C:\MsLogs\ /E
Note: If IIS is using the Shared Configuration feature, then applicationHost.config should be collected from the network location where the file is shared.
IIS Log files
Only send logs of the site containing the problematic application. Default location:
C:\inetpub\logs\LogFiles\W3SVC[siteID]\
Determine the Site ID from IIS Manager console, selecting the Sites node.
Only include latest files, if too many logs are there; we only need the investigated timeframe. For instance, logs in the last 10 days.
Example:
MKDIR C:\MsLogs\IIS-logs
ROBOCOPY C:\inetpub\logs\LogFiles\W3SVC1\ C:\MsLogs\IIS-logs\ /MAXAGE:10
FREBs, Failed Request Traces…
…if any were collected at all, related to the issue being reported.
Only send traces for the site containing the problematic application. Default location:
C:\inetpub\logs\FailedReqLogFiles\W3SVC[siteID]\
Determine the Site ID from IIS Manager console, selecting the Sites node.
Example:
MKDIR C:\MsLogs\FREBs
COPY C:\inetpub\logs\FailedReqLogFiles\W3SVC1\*.* C:\MsLogs\FREBs\
HttpErr logs
Events and errors logged by the HTTP.SYS driver, which IIS relies on. The default location:
C:\Windows\System32\LogFiles\HTTPERR\
Only include latest files, if too many logs are there; we only need the investigated timeframe. For instance, logs in the last 10 days.
Example:
MKDIR C:\MsLogs\HTTPERR
ROBOCOPY %systemroot%\System32\LogFiles\HTTPERR\ C:\MsLogs\HTTPERR\ /MAXAGE:10
The .NET configuration and root Web.config
Before executing an app, IIS is building its configuration by merging trees with settings — read «config files»: .NET FX config, then Asp.NET root Web.config, applicationHost.config of IIS, application’s local Web.config cascade (root site Web.config, then sub-application’s Web.config etc).
The .NET Framework (FX) configuration:
machine.config
The root ASP.NET configuration:
Web.config
Depending on application bitness, these can be found at:
C:\Windows\Microsoft.NET\Framework(64)\[version]\Config
Example:
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config
It’s better if you can send the whole folder.
Example:
MKDIR C:\MsLogs\ASP.NET-Config
XCOPY %systemroot%\Microsoft.NET\Framework64\v4.0.30319\Config\*.* C:\MsLogs\ASP.NET-Config\ /E
Application’s local configuration
The Web.config file(s) of the root site — and sub-application(s), if that’s the case — being diagnosed.
Or at least send the application’s effective configuration, compiled by IIS from the above config files:
C:\inetpub\temp\appPools\[appPoolName]\[appPoolName].config
Example:
COPY C:\inetpub\temp\appPools\DefaultAppPool\DefaultAppPool.config C:\MsLogs\
Windows Events Viewer entries
We’ll take the following 3 logs from Windows Events Viewer
- Application Event logs
- System Event logs
- Security Event logs
- Setup Event logs
Select each of them and then…
- On the right side, pick Filter Current Log…, then only last 7 or 30 days
(make sure the period covers moment when issue was manifesting). - Then, on the right side again, pick Save Filtered Log File As… EVTX,
(make sure you include ‘Display information for these languages: English‘)
To collect entries in last 10 days, you can export them by running the following command lines:
WEVTUTIL export-log System C:\MsLogs\WinEvents-System.evtx /query:"*[System[TimeCreated[timediff(@SystemTime) <= 864000000]]]"
WEVTUTIL export-log Application C:\MsLogs\WinEvents-Application.evtx /query:"*[System[TimeCreated[timediff(@SystemTime) <= 864000000]]]"
WEVTUTIL export-log Security C:\MsLogs\WinEvents-Security.evtx /query:"*[System[TimeCreated[timediff(@SystemTime) <= 864000000]]]"
WEVTUTIL export-log Setup C:\MsLogs\WinEvents-Setup.evtx /query:"*[System[TimeCreated[timediff(@SystemTime) <= 864000000]]]"
Note that timediff function returns milliseconds from now. One day means 24 hours x 60 minutes x 60 seconds x 1.000 milliseconds = 86.400.000.
IIS installation logs
Collect Component-Based Setup log file — the packages that Windows installed.
Then IIS setup logs — how the IIS instance installation went.
COPY C:\Windows\Logs\CBS\cbs.log C:\MsLogs\
COPY C:\Windows\iis.log C:\MsLogs\
System information
Export the output of MsInfo32, or simply run the command:
MsInfo32 /nfo C:\MsLogs\System-Info.nfo
MsInfo32 /report C:\MsLogs\System-Info.txt
Export the Registry keys telling about .NET Framework version(s) installed on machine:
Reg.exe export "HKLM\SOFTWARE\Microsoft\NET Framework Setup\NDP" C:\MsLogs\NET-Frameworks-versions.reg.txt
Archive the resulting data collection folder C:\MsLogs\ in a ZIP file, then upload the archive in the file transfer space for the case.
You’ll need to send the collected data and/or share it with the engineer helping you do the troubleshooting.
Application issue details
You have to provide as much descriptive information as you can around what happens.
- Please provide the name of the site and/or application with the problem and also the Application Pool name;
- The affected URLs, possibly with screenshots or HTTP traces from client;
- Observed behavior, such as long response time, high-memory consumption or high-CPU;
- What the application is supposed to do, or what are the URLs exerting the problem are doing;
- Reproducing steps, if applicable;
- Any pattern of usage that triggers the behavior: certain time of day, certain users, certain system conditions etc.
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%\inetpub\logs\LogFiles
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%\Windows\System32\LogFiles\HTTPERR
Which will contain similar log files that only represents errors.
answered Jun 21, 2011 at 13:51
jishijishi
24.2k6 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
19k23 gold badges72 silver badges108 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%\inetpub\logs\LogFiles\W3SVC4
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,6561 gold badge18 silver badges21 bronze badges
1
The 100% correct answer for the default location of the log files is…
%SystemDrive%\inetpub\logs\LogFiles
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,5474 gold badges52 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,5162 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,75124 silver badges37 bronze badges
I think the Default place for IIS logging is: c:\inetpub\wwwroot\log\w3svc
Kjartan
18.6k15 gold badges71 silver badges96 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:\inetpub\logs\LogFiles\
which help to fix my issue.
answered Dec 2, 2017 at 4:47
Hiren ParghiHiren Parghi
1,7951 gold badge21 silver badges30 bronze badges
1
C:\inetpub\logs\LogFiles
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 $GetIISLogs\W3SVC1\*
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
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 56,618 times.
Is this article up to date?
Добрый день! Уважаемые читатели и гости IT блога Pyatilistnik.org. В прошлый раз мы с вами рассматривали, как можно установить Internet Information Services. Сегодня я хочу продолжить данную тему и показать вам где хранятся файлы журналов IIS, так как файлы журналов Internet Information Services (IIS) содержат ценную информацию об использовании и состоянии Web приложений. Однако не всегда легко найти, где они находятся, чтобы определить важные аспекты использования приложения, например, когда были сделаны запросы к серверу, кем и другие проблемы пользовательского трафика.