Log Files for a Web Site <logFile>

Overview

The <logFile> element of the <site> element contains attributes that allow you to configure logging for a site on Internet Information Services (IIS) 7.

For example, you can enable or disable logging, configure the format of the IIS log file, specify the categories of information to store in the log file, and change the directory where the log file is stored. You can also use the <logFile> element to control how often IIS creates a new log file based either on log file size or time interval and the maximum size (in bytes) that a log file can become.

By default, IIS 7 uses the World Wide Web Consortium (W3C) log file format. You can change this setting by modifying the logFormat attribute to IIS, NCSA, or Custom.

Note: ODBC logging is implemented as a custom logging module in IIS 7, therefore enabling and configuring ODBC logging in IIS 7 consists of two separate actions:

  • Setting the ODBC logging attributes in the <odbcLogging> element. These attributes specify the System Data Source Name (DSN), table name, user name, and password for the ODBC connection.
  • Setting the correct custom logging attributes in <logFile> element. These attributes must set the log file format to "Custom" and the custom log plug-in class ID to "{FF16065B-DE82-11CF-BC0A-00AA006111E0}".

For more information about ODBC logging, see the <odbcLogging> element.

You can define the categories of information that IIS logs by editing the logExtFileFlags attribute. The default values are Date, Time, ClientIP, UserName, ServerIP, Method, UriStem, UriQuery, TimeTaken, HttpStatus, Win32Status, ServerPort, UserAgent, and HttpSubStatus.

Note: If the <logFile> element is configured in both the <siteDefaults> section and in the <site> section for a specific site, the configuration in the <site> section is used for that site.

Compatibility

Version Notes
IIS 7.5 The <logFile> element was not modified in IIS 7.5.
IIS 7.0 The <logFile> element of the <site> element was introduced in IIS 7.0.
IIS 6.0 The <logFile> element replaces sections of the logging properties on the IIS 6.0 IIsWebService metabase object.

Setup

The <logFile> element is included in the default installation of IIS 7.

How To

How to edit logging settings for a site

  1. Open Internet Information Services (IIS) Manager:
    • If you are using Windows Server 2008 or Windows Server 2008 R2:
      • On the taskbar, click Start, point to Administrative Tools, and then click Internet Information Services (IIS) Manager.
    • If you are using Windows Vista or Windows 7:
      • On the taskbar, click Start, and then click Control Panel.
      • Double-click Administrative Tools, and then double-click Internet Information Services (IIS) Manager.
  2. In the Connections pane, expand the server name, expand Sites, and then click the Web site on which you want to configure logging.
  3. In the Home pane, double-click Logging.
  4. In the Logging pane, select the log file format in the Format box, and then type the path to the directory where you store the log files in the Directory box or click Browse... to choose the directory in which to store the log files.
  5. If you choose to use the W3C log file format:
    • Click Select Fields to choose the types of information to log.
    • In the W3C Logging Fields dialog box, select the check boxes for options you want to log, clear the check boxes for options you do not want to log, and then click OK.

Configuration

Attributes

Attribute Description
customLogPluginClsid Optional string attribute.

Specifies the COM object class ID (CLSID) or IDs, in order of precedence, for custom modules.
directory Optional string attribute.

Specifies the logging directory, where the log file and logging-related support files are stored.

The default value is %SystemDrive%\inetpub\logs\LogFiles.
enabled Optional Boolean attribute.

Specifies whether logging is enabled (true) or disabled (false) for a site.

Note: ASP and ODBC errors are not logged in the IIS log files.

The default value is true.
localTimeRollover Optional Boolean attribute.

Specifies whether a new log file is created based on local time or Coordinated Universal Time (UTC), which was previously called Greenwich Mean Time (GMT). When false, a new log file is created based on UTC.

Note: Regardless of the setting, the time stamp for each W3C Extended Logging log record is UTC-based.

The default value is false.
logExtFileFlags Optional flags attribute.

Specifies the categories of information that are written to either the log file (when you use W3C Extended log file format) or to the ODBC data source during logging events for a site. The logExtFileFlags attribute can be one or more of the following values. If you specify more than one value, separate them with a comma (,).

The default values are Date, Time, ClientIP, UserName, ServerIP, Method, UriStem, UriQuery, TimeTaken, HttpStatus, Win32Status, ServerPort, UserAgent, HttpSubStatus.
Value Description
BytesRecv Log the number of bytes that the server received.
BytesSent Log the number of bytes that the server sent.
ClientIP Log the IP address of the client that made the request.
ComputerName Log the name of the server on which the log file entry was generated.
Cookie Log the content of the cookie that was sent or received, if any content exists.
Date Log the date on which the activity occurred.
Host Log the host header name, if there is one.
HttpStatus Log the HTTP status code.
HttpSubStatus Log the sub-status code of the HTTP error. For example, for the 500.18 HTTP error, the status code is 500 and the sub-status code is 18.
Method Log the requested action. For example, GET, POST, etc.
ProtocolVersion Log the protocol version that the client used.
Referer Log the site that the user last visited. This site provided a link to the current site.
ServerIP Log the IP address of the server on which the log file entry was generated.
ServerPort Log the server port number that is configured for the site.
SiteName Log the Internet service name and instance number for the site.
Time Log the time in Coordinated Universal Time (UTC), at which the activity occurred.
TimeTaken Log the length of time taken for a request to be completed. The time taken is recorded in milliseconds.

Note: The client-request timestamp is initialized when HTTP.sys receives the first byte, but before HTTP.sys begins to parse the request. The client-request timestamp is stopped when the last IIS send completion occurs. Time taken does not reflect time across the network. The first request to the site shows a slightly longer time taken than other similar requests because HTTP.sys opens the log file that contains the first request.
UriQuery Log the query, if any, that the client was trying to perform. A Universal Resource Identifier (URI) query is necessary only for dynamic pages, and usually consists of parameters passed to the URL.
UriStem Log the Universal Resource Identifier (URI) stem information, which is the target of the action. For example, Default.htm.
UserAgent Log the browser type that the client used.
UserName Log the name of the authenticated user who accessed your server. Anonymous users are indicated by a hyphen.
Win32Status Log the Windows status code.
logFormat Optional enum attribute.

Specifies the log file format. The logFormat attribute can be one of the following values.

The default value is W3C.
Value Description
Custom Use a custom log file format for a custom logging module.

The numeric value is 3.
IIS Use the Microsoft IIS log file format to log information about a site. This format is handled by HTTP.sys, and is a fixed ASCII text-based format, which means that you cannot customize the fields that are logged. Fields are separated by commas, and time is recorded as local time. The following list is a list of fields that are logged when you use the IIS log file format:
  • Client IP address
  • User name
  • Date
  • Time
  • Service and instance
  • Server name
  • Server IP address
  • Time taken
  • Client bytes sent
  • Server bytes sent
  • Service status code (A value of 200 indicates that the request was fulfilled successfully.)
  • Windows status code (A value of 0 indicates that the request was fulfilled successfully.)
  • Request type
  • Target of operation
  • Parameters (the parameters that are passed to a script)
Not all fields will contain data. When a field does not contain data, a hyphen (-) appears as a placeholder. When a field contains a non-printable character, HTTP.sys replaces it with a plus sign (+) to preserve the log file format.

The numeric value is 0.
NCSA Use the National Center for Supercomputing Applications (NCSA) Common log file format to log information about a site. This format is handled by HTTP.sys, and is a fixed ASCII text-based format, which means that you cannot customize the fields that are logged. Fields are separated by spaces, and time is recorded as local time with the Coordinated Universal Time (UTC) offset. The following list is a list of fields that are logged when you use the NCSA Common log file format:
  • Remote host address
  • Remote log name (This value is always a hyphen.)
  • User name
  • Date, time, and UTC offset
  • Request and protocol version
  • Service status code (A value of 200 indicates that the request was fulfilled successfully.)
  • Bytes sent
Not all fields will contain data. When a field does not contain data, a hyphen (-) appears as a placeholder. When a field contains a non-printable character, HTTP.sys replaces it with a plus sign (+) to preserve the log file format.

The numeric value is 1.
W3C Use the W3C Extended log file format to log information about a site. This format is handled by HTTP.sys, and is a customizable ASCII text-based format, which means that you specify the fields that are logged. Specify the fields that are logged in the logExtFileFlags attribute. Fields are separated by spaces, and time is recorded in Coordinated Universal Time (UTC).

The numeric value is 2.
period Optional enum attribute.

Specifies how often IIS creates a new log file. The period attribute can be one of the following possible values.

The default value is Daily.
Value Description
Daily Create a new log file daily.

The numeric value is 1.
Hourly Create a new log file hourly.

The numeric value is 4.
MaxSize Create a new log file when a maximum size is reached. The maximum size is specified in the truncateSize attribute.

The numeric value is 0.
Monthly Create a new log file monthly.

The numeric value is 3.
Weekly Create a new log file weekly.

The numeric value is 2.
truncateSize Optional int64 attribute.

Specifies the maximum size of the log file (in bytes) after which to create a new log file. This value is only applicable when MaxSize is chosen for the period attribute. The minimum file size is 1,048,576 bytes. If this attribute is set to a value less than 1,048,576 bytes, the default value is implicitly assumed as 1,048,576 bytes.

The default value is 20971520.

Child Elements

None.

Configuration Sample

The following configuration example uses the logExtFileFlags attribute of the <logFile> element to specify the settings that IIS logs for a Web site named Contoso. The period attribute causes IIS to create a new W3C log file every hour; the localTimeRollover attribute specifies that IIS use the time on the local server to determine when to create and name a new log file.

<site name="Contoso" id="2" serverAutoStart="true">
   <application path="/" applicationPool="Contoso">
      <virtualDirectory path="/" physicalPath="C:\Contoso\Content" />
   </application>
   <bindings>
      <binding protocol="http" bindingInformation="*:80:www.contoso.com" />
   </bindings>
   <logFile
      period="Hourly"
      localTimeRollover="true"
      logExtFileFlags="Date, Time, ClientIP, UserName, ServerIP, Method, UriStem, UriQuery, HttpStatus, TimeTaken, ServerPort, UserAgent, HttpSubStatus" />
</site>

Sample Code

The following examples configure logging for a site named Contoso. Each example enables logging for the site and configures site logging to generate a new log file on a daily basis. They also configure IIS to use the time on the local server to generate the log file names and determine when to generate new log files.

AppCmd.exe

appcmd.exe set config -section:system.applicationHost/sites /[name='Contoso'].logFile.logFormat:"W3C" 
appcmd.exe set config -section:system.applicationHost/sites /[name='Contoso'].logFile.period:"Daily" 
appcmd.exe set config -section:system.applicationHost/sites /[name='Contoso'].logFile.localTimeRollover:"True" 
appcmd.exe set config -section:system.applicationHost/sites /[name='Contoso'].logFile.enabled:"True" /commit:apphost

Note: You must be sure to set the commit parameter to apphost when you use AppCmd.exe to configure these settings. This commits the configuration settings to the appropriate location section in the ApplicationHost.config file.

C#

using System;
using System.Text;
using Microsoft.Web.Administration;

internal static class Sample
{
   private static void Main()
   {
      using (ServerManager serverManager = new ServerManager())
      {
         Configuration config = serverManager.GetApplicationHostConfiguration();
         ConfigurationSection sitesSection = config.GetSection("system.applicationHost/sites");
         ConfigurationElementCollection sitesCollection = sitesSection.GetCollection();

         ConfigurationElement siteElement = FindElement(sitesCollection, "site", "name", @"Contoso");
         if (siteElement == null) throw new InvalidOperationException("Element not found!");

         ConfigurationElement logFileElement = siteElement.GetChildElement("logFile");
         logFileElement["logFormat"] = @"W3C";
         logFileElement["period"] = @"Daily";
         logFileElement["localTimeRollover"] = true;
         logFileElement["enabled"] = true;

         serverManager.CommitChanges();
      }
   }

   private static ConfigurationElement FindElement(ConfigurationElementCollection collection, string elementTagName, params string[] keyValues)
   {
      foreach (ConfigurationElement element in collection)
      {
         if (String.Equals(element.ElementTagName, elementTagName, StringComparison.OrdinalIgnoreCase))
         {
            bool matches = true;
            for (int i = 0; i < keyValues.Length; i += 2)
            {
               object o = element.GetAttributeValue(keyValues[i]);
               string value = null;
               if (o != null)
               {
                  value = o.ToString();
               }
               if (!String.Equals(value, keyValues[i + 1], StringComparison.OrdinalIgnoreCase))
               {
                  matches = false;
                  break;
               }
            }
            if (matches)
            {
               return element;
            }
         }
      }
      return null;
   }
}

VB.NET

Imports System
Imports System.Text
Imports Microsoft.Web.Administration

Module Sample
   Sub Main()
       Dim serverManager As ServerManager = New ServerManager
       Dim config As Configuration = serverManager.GetApplicationHostConfiguration
       Dim sitesSection As ConfigurationSection = config.GetSection("system.applicationHost/sites")
       Dim sitesCollection As ConfigurationElementCollection = sitesSection.GetCollection
       Dim siteElement As ConfigurationElement = FindElement(sitesCollection, "site", "name", "Contoso")

       If (siteElement Is Nothing) Then
          Throw New InvalidOperationException("Element not found!")
       End If

       Dim logFileElement As ConfigurationElement = siteElement.GetChildElement("logFile")
       logFileElement("logFormat") = "W3C"
       logFileElement("period") = "Daily"
       logFileElement("localTimeRollover") = True
       logFileElement("enabled") = True

       serverManager.CommitChanges()
   End Sub

   Private Function FindElement(ByVal collection As ConfigurationElementCollection, ByVal elementTagName As String, ByVal ParamArray keyValues() As String) As ConfigurationElement
      For Each element As ConfigurationElement In collection
         If String.Equals(element.ElementTagName, elementTagName, StringComparison.OrdinalIgnoreCase) Then
            Dim matches As Boolean = True
            Dim i As Integer
            For i = 0 To keyValues.Length - 1 Step 2
               Dim o As Object = element.GetAttributeValue(keyValues(i))
               Dim value As String = Nothing
               If (Not (o) Is Nothing) Then
                  value = o.ToString
               End If
               If Not String.Equals(value, keyValues((i + 1)), StringComparison.OrdinalIgnoreCase) Then
                  matches = False
                  Exit For
               End If
            Next
            If matches Then
               Return element
            End If
         End If
      Next
      Return Nothing
   End Function

End Module

JavaScript

var adminManager = new ActiveXObject('Microsoft.ApplicationHost.WritableAdminManager');
adminManager.CommitPath = "MACHINE/WEBROOT/APPHOST";
var sitesSection = adminManager.GetAdminSection("system.applicationHost/sites", "MACHINE/WEBROOT/APPHOST");
var sitesCollection = sitesSection.Collection;

var siteElementPos = FindElement(sitesCollection, "site", ["name", "Contoso"]);
if (siteElementPos == -1) throw "Element not found!";

var siteElement = sitesCollection.Item(siteElementPos);
var logFileElement = siteElement.ChildElements.Item("logFile");
logFileElement.Properties.Item("logFormat").Value = "W3C";
logFileElement.Properties.Item("period").Value = "Daily";
logFileElement.Properties.Item("localTimeRollover").Value = true;
logFileElement.Properties.Item("enabled").Value = true;

adminManager.CommitChanges();

function FindElement(collection, elementTagName, valuesToMatch) {
   for (var i = 0; i < collection.Count; i++) {
      var element = collection.Item(i);
      if (element.Name == elementTagName) {
         var matches = true;
         for (var iVal = 0; iVal < valuesToMatch.length; iVal += 2) {
            var property = element.GetPropertyByName(valuesToMatch[iVal]);
            var value = property.Value;
            if (value != null) {
               value = value.toString();
            }
            if (value != valuesToMatch[iVal + 1]) {
               matches = false;
               break;
            }
         }
         if (matches) {
            return i;
         }
      }
   }
   return -1;
}

VBScript

Set adminManager = createObject("Microsoft.ApplicationHost.WritableAdminManager")
adminManager.CommitPath = "MACHINE/WEBROOT/APPHOST"
Set sitesSection = adminManager.GetAdminSection("system.applicationHost/sites", "MACHINE/WEBROOT/APPHOST")
Set sitesCollection = sitesSection.Collection
siteElementPos = FindElement(sitesCollection, "site", Array("name", "Contoso"))

If siteElementPos = -1 Then
   WScript.Echo "Element not found!"
   WScript.Quit
End If

Set siteElement = sitesCollection.Item(siteElementPos)
Set logFileElement = siteElement.ChildElements.Item("logFile")
logFileElement.Properties.Item("logFormat").Value = "W3C"
logFileElement.Properties.Item("period").Value = "Daily"
logFileElement.Properties.Item("localTimeRollover").Value = True
logFileElement.Properties.Item("enabled").Value = True

adminManager.CommitChanges()

Function FindElement(collection, elementTagName, valuesToMatch)
   For i = 0 To CInt(collection.Count) - 1
      Set element = collection.Item(i)
      If element.Name = elementTagName Then
         matches = True
         For iVal = 0 To UBound(valuesToMatch) Step 2
            Set property = element.GetPropertyByName(valuesToMatch(iVal))
            value = property.Value
            If Not IsNull(value) Then
               value = CStr(value)
            End If
            If Not value = CStr(valuesToMatch(iVal + 1)) Then
               matches = False
               Exit For
            End If
         Next
         If matches Then
            Exit For
         End If
      End If
   Next
   If matches Then
      FindElement = i
   Else
      FindElement = -1
   End If
End Function
Deprecated Elements