Home / Guides / Search IIS logs on multiple servers
Search IIS logs on many web servers at once
A page returned errors for an hour last night, your site runs on several web servers behind a load balancer, and each one wrote its own IIS log. This guide covers where IIS keeps those logs and why their times look wrong, a PowerShell script that searches the logs of a list of servers and puts the matching requests in one sorted list, what the read needs, the requests that never reach the IIS log, and where the script stops.
Short answer.
IIS writes one text log per site per day under C:\inetpub\logs\LogFiles\W3SVC<site id>. Read those files from each
server over its admin share (\\WEB01\C$\inetpub\logs\LogFiles), take the column names from the #Fields: line,
filter on status code, URL and time, and sort everything into one list. The times in the file are UTC, and the newest requests can sit
in a buffer for a while before they reach the file.
This searches what is still on the servers right now. Requests that HTTP.sys rejected before IIS saw them are in a different log (HTTPERR).
Where IIS writes its logs
By default IIS keeps one log per site (the One log file per: Site setting) in W3C format. The folder is
%SystemDrive%\inetpub\logs\LogFiles, with a subfolder per site named after the site id: W3SVC1 for the Default
Web Site, W3SVC2 for the next one, and so on. A new file starts every day (by UTC date, unless the site is set to use local time), named
u_exYYMMDD.log. The folder can be changed per server or per site in IIS Manager
(Logging, Directory), so check before you assume. This lists every site's log folder on several servers:
Invoke-Command -ComputerName WEB01, WEB02 -ScriptBlock {
Import-Module WebAdministration
Get-Website | Select-Object Name, Id,
@{ n = 'LogFolder'; e = { [Environment]::ExpandEnvironmentVariables($_.logFile.directory) + "\W3SVC$($_.Id)" } }
} | Format-Table PSComputerName, Name, Id, LogFolder -AutoSize
Three things about the files catch everyone once:
- The times are UTC. The
dateandtimecolumns of a W3C log are always UTC, whatever the server's time zone. The Use local time for file naming and rollover option only changes when a new file starts and its name, not the times inside it. - The columns can differ. Each file starts with
#lines, and#Fields:names the columns. Which ones are there depends on the fields chosen under Select Fields, so read that line instead of counting columns. When the field list changes, IIS writes a new#Fields:line, also in the middle of a file. - The newest requests may not be in the file yet. HTTP.sys buffers log entries and writes them in blocks. On a quiet test
server, run
netsh http flush logbufferin an elevated window to write them out now.
Search several servers with PowerShell
The script below reads the u_ex*.log files under each server's log folder, skips files that were not written to since the
start time, and checks every line against the filters. The file of the current day is open in IIS, so the script opens it with shared
read and write access, the way Notepad would. Each result has the server, the site folder, the URL, the status with its substatus,
the time taken and the client address.
param(
[string[]]$ComputerName = @('WEB01', 'WEB02'),
[string]$LogFolder = '\\{0}\C$\inetpub\logs\LogFiles', # {0} = server name; a local path works too
[datetime]$StartTime = (Get-Date).AddHours(-24),
[int[]]$Status = @(), # for example 500, 503; empty = any status
[string]$Text = '' # part of the URL, query or user agent; empty = all
)
$startUtc = $StartTime.ToUniversalTime()
$culture = [System.Globalization.CultureInfo]::InvariantCulture
$utc = [System.Globalization.DateTimeStyles]'AssumeUniversal, AdjustToUniversal'
$found = [System.Collections.Generic.List[object]]::new()
foreach ($computer in $ComputerName) {
$root = $LogFolder -f $computer
try {
# u_ex*.log = the W3C log of each site (one W3SVC<site id> folder per site).
# Only files written to since the start time can hold matching lines.
$files = Get-ChildItem -Path $root -Filter 'u_ex*.log' -Recurse -File -ErrorAction Stop |
Where-Object { $_.LastWriteTimeUtc -ge $startUtc }
}
catch {
Write-Warning "${computer}: $($_.Exception.Message)"
continue
}
foreach ($file in $files) {
try {
# IIS keeps today's file open for writing, so open it with FileShare ReadWrite.
$stream = [System.IO.FileStream]::new($file.FullName, 'Open', 'Read', 'ReadWrite')
$reader = [System.IO.StreamReader]::new($stream)
}
catch {
Write-Warning "${computer}: $($file.FullName): $($_.Exception.Message)"
continue
}
try {
$fields = $null
while ($null -ne ($line = $reader.ReadLine())) {
if ($line.StartsWith('#')) {
# The field list can change in the middle of a file, so always use the latest one.
if ($line.StartsWith('#Fields: ')) { $fields = $line.Substring(9).Trim().Split(' ') }
continue
}
if (-not $fields -or $line.Length -eq 0) { continue }
# Cheap text check before splitting the line.
if ($Text -and $line.IndexOf($Text, [System.StringComparison]::OrdinalIgnoreCase) -lt 0) { continue }
$values = $line.Split(' ')
$row = @{}
for ($i = 0; $i -lt $fields.Count -and $i -lt $values.Count; $i++) { $row[$fields[$i]] = $values[$i] }
# date and time are in UTC in every W3C log, whatever the rollover setting.
$timeUtc = [datetime]::ParseExact("$($row['date']) $($row['time'])", 'yyyy-MM-dd HH:mm:ss', $culture, $utc)
if ($timeUtc -lt $startUtc) { continue }
if ($Status.Count -and [int]$row['sc-status'] -notin $Status) { continue }
if ($Text) {
$where = "$($row['cs-uri-stem']) $($row['cs-uri-query']) $($row['cs(User-Agent)'])"
if ($where.IndexOf($Text, [System.StringComparison]::OrdinalIgnoreCase) -lt 0) { continue }
}
$found.Add([pscustomobject]@{
Time = $timeUtc.ToLocalTime()
Computer = $computer
Site = $file.Directory.Name # W3SVC<site id>
Method = $row['cs-method']
Url = $row['cs-uri-stem']
Query = $row['cs-uri-query']
Status = "$($row['sc-status']).$($row['sc-substatus'])"
Win32 = $row['sc-win32-status']
TimeMs = $row['time-taken']
ClientIP = $row['c-ip']
UserAgent = $row['cs(User-Agent)']
})
}
}
finally {
$reader.Dispose()
}
}
}
$found | Sort-Object Time -Descending
Save it as C:\Scripts\Search-IisLogs.ps1 and run it with your own server names:
# Every 500-type error on three web servers in the last 6 hours:
C:\Scripts\Search-IisLogs.ps1 -ComputerName WEB01, WEB02, WEB03 -Status 500, 502, 503 -StartTime (Get-Date).AddHours(-6) |
Format-Table Time, Computer, Site, Method, Url, Status, TimeMs -AutoSize
# Every request to /api/orders since yesterday, to a CSV file, with the server list in a file:
C:\Scripts\Search-IisLogs.ps1 -ComputerName (Get-Content C:\Scripts\webservers.txt) -Text '/api/orders' -StartTime (Get-Date).AddDays(-1) |
Export-Csv "$env:USERPROFILE\Desktop\IisLogSearch.csv" -NoTypeInformation -Encoding UTF8
# Which URLs failed most:
C:\Scripts\Search-IisLogs.ps1 -ComputerName WEB01, WEB02 -Status 500 | Group-Object Url | Sort-Object Count -Descending
-ComputerName: the web servers to search.-LogFolder: the log folder as a path, with{0}where the server name goes. The default is the admin share of the default folder.-StartTime: how far back to look, in your local time (default 24 hours). The script converts it to UTC before it compares.-Status: the HTTP status codes to keep, for example500, 502, 503. Leave it out to get every status.-Text: part of the URL, the query string or the user agent, not case-sensitive.
The output is a list of objects, so Export-Csv, Group-Object and Format-Table work on it. To see which
URLs failed most, group by Url; to see whether one server is the problem, group by Computer.
Tested on Windows PowerShell 5.1 on Windows 11 with IIS 10 and two sites: the script read both sites' logs over the C$ admin share under two names for the same computer and returned one list, newest first, in local time; the status filter, a list of statuses and the text search (query string and user agent, in any case) matched the right requests; today's file was read while IIS had it open (File.ReadAllLines fails on it, which is why the script opens it with shared access); a field list changed during the day was read from the new #Fields: line; a request did not reach the file until netsh http flush logbuffer; a server name that does not exist gave a warning and the other server was still searched. Invoke-Command -FilePath with the positional arguments and the folder listing were run against the test computer itself, and the HTTPERR search found the 503 of a stopped application pool. Reading other servers over the network is from Microsoft's documentation and was not tested.
Faster on many servers: Invoke-Command
Reading over the share copies every line across the network before it is checked, which is slow with large logs on many servers.
Invoke-Command -FilePath sends the same script to the servers and runs it there, up to 32 at a time by default, so only the
matching lines come back. The arguments are positional, in the order of the param block, and the log folder is now a local path:
$servers = Get-Content C:\Scripts\webservers.txt
Invoke-Command -ComputerName $servers -FilePath C:\Scripts\Search-IisLogs.ps1 `
-ArgumentList 'localhost', 'C:\inetpub\logs\LogFiles', (Get-Date).AddHours(-6), @(500, 502, 503) |
Sort-Object Time -Descending |
Select-Object PSComputerName, Time, Site, Method, Url, Status, TimeMs, ClientIP |
Export-Csv "$env:USERPROFILE\Desktop\IisLogSearch.csv" -NoTypeInformation -Encoding UTF8
This needs PowerShell remoting (WinRM) on the servers and an account in their Administrators or Remote Management Users group, and the
account must be able to read the log folder there. PSComputerName holds the real server name, and the times are in each
server's own time zone.
What the read needs
- Access to the folder. The
C$admin share needs an account that is an administrator on the server. If you would rather not use one, share the log folder itself read-only to a group, and point-LogFolderat that share (for example\\{0}\IisLogs). - File sharing through the network. SMB, TCP port 445, from your computer to every server.
- The same folder on every server. If one server keeps its logs on another drive, search it in a separate run with its own
-LogFolder.
Requests that never reach the IIS log
HTTP.sys, the kernel driver in front of IIS, rejects some requests before IIS sees them: malformed requests (400), requests to an
application pool that is stopped or crashing (503), connections that time out. Those are written to the HTTPERR log, by default
%SystemRoot%\System32\LogFiles\HTTPERR\httperr*.log, with a reason in the s-reason column: for example
Header for a malformed header, Disabled for a stopped application pool, QueueFull when the pool's
request queue is full, and Connection_Abandoned_By_AppPool when a worker process crashed with requests waiting. Its times
are UTC too, and only administrators can read the folder. When
users see 503 errors that are not in the IIS log, look here:
foreach ($server in 'WEB01', 'WEB02') {
Select-String -Path "\\$server\C$\Windows\System32\LogFiles\HTTPERR\httperr*.log" `
-Pattern ' 503 ', 'QueueFull', 'AppOffline', 'Connection_Abandoned_By_AppPool' |
Select-Object @{ n = 'Computer'; e = { $server } }, Filename, Line
}
Where the script stops
- Only what is still on the server. IIS does not delete old logs, so many servers run a clean-up job; whatever it removed is gone. A server that was replaced or rebuilt takes its logs with it.
- Not live. Buffered entries reach the file after a delay, and the script reads the files once. Run it again to see what happened since.
- Slow on big logs. Every run reads the matching files again from the start. A day of a busy site can be hundreds of megabytes per server.
- Only IIS. The Windows Event Log (application pool crashes, WAS warnings) and your application's own log files are separate searches.
Questions
Where are the IIS log files?
By default in %SystemDrive%\inetpub\logs\LogFiles, in one folder per site named W3SVC plus the site id (W3SVC1 is usually the Default Web Site), one file per day named u_exYYMMDD.log. The folder can be changed per server or per site under Logging in IIS Manager, and Get-Website in the WebAdministration module shows each site's logFile.directory.
Why are the times in my IIS log hours off?
W3C logs record the date and time in UTC, whatever the server's time zone. The option Use local time for file naming and rollover only changes when a new file starts and how it is named. Convert the time to local time when you read it, as the script in this guide does.
Why is a request I just made not in the IIS log yet?
HTTP.sys buffers log entries and writes them to the file in blocks, so on a quiet server the newest requests can be missing for a while. On a test server, netsh http flush logbuffer in an elevated window writes them out at once.
Why is a 503 or 400 error not in the IIS log?
Some requests are rejected by HTTP.sys before IIS sees them, for example when the application pool is stopped or the request is malformed. They are written to the HTTPERR log in %SystemRoot%\System32\LogFiles\HTTPERR instead, with a reason such as Disabled (a stopped application pool), QueueFull or Header in the s-reason column.
Can I search IIS logs on many servers without PowerShell remoting?
Yes. Read the log files over a file share, either the C$ admin share (needs an administrator account on the server) or a read-only share of the log folder, as the script in this guide does. PowerShell remoting with Invoke-Command is faster on large logs because the search runs on each server, but it is not required.
Related
- Search Windows Event Logs on multiple servers at once
- LogTrawler: all your server logs in one searchable place
- All guides
Sources (Microsoft Learn): Configure logging in IIS, Default log file settings for web sites (logFile), The log element (central logging, UTF-8), Managing IIS log file storage, netsh http (flush logbuffer), Configuring HTTP Server API error logging, Types of errors logged by the HTTP Server API, Troubleshoot 4xx and 5xx HTTP errors, Invoke-Command, Select-String.