Event Logging (Windows Installer)
Windows Events provides a standard, centralized way for applications (and the operating system) to record important software and hardware events. The event-logging service stores events from various sources in a single collection called an event log. Prior to WindowsВ Vista, you would use either Event Tracing for Windows (ETW) or Event Logging to log events. WindowsВ Vista introduced a new eventing model that unifies both ETW and the Windows Event Log API.
The installer also writes entries into the event log. These record events such as following:
- Success or failure of the installation; removal or repair of a product.
- Errors that occur during product configuration.
- Detection of corrupted configuration data.
If a large amount of information is written, the Event Log file can become full and the installer displays the message, «The Application log file is full.»
The installer may write the following entries in the event log. All event log messages have a unique event ID. All general errors authored in the Error table that are returned for an installation that fails are logged in the Application Event Log with a message ID equal to the Error + 10,000. For example, the error number in the Error table for an installation completed successfully is 1707. The successful installation is logged in the Application Event Log with a message ID of 11707 (1707 + 10,000).
For information about how to enable verbose logging on a user’s computer when troubleshooting deployment, see Windows Installer Best Practices.
WMI Tasks: Event Logs
WMI tasks for event logs obtain event data from event log files and perform operations like backing up or clearing log files. For other examples, see the TechNet ScriptCenter at https://www.microsoft.com/technet.
The script examples shown in this topic obtain data only from the local computer. For more information about how to use the script to obtain data from remote computers, see Connecting to WMI on a Remote Computer.
The following procedure describes how to run a script.
To run a script
- Copy the code and save it in a file with a .vbs extension, such as filename.vbs. Ensure that your text editor does not add a .txt extension to the file.
- Open a command prompt window and navigate to the directory where you saved the file.
- Type cscript filename.vbs at the command prompt.
- If you cannot access an event log, check to see if you are running from an Elevated command prompt. Some Event Log, such as the Security Event Log, may be protected by User Access Controls (UAC).
By default, cscript displays the output of a script in the command prompt window. Because WMI scripts can produce large amounts of output, you might want to redirect the output to a file. Type cscript filename.vbs > outfile.txt at the command prompt to redirect the output of the filename.vbs script to outfile.txt.
The following table lists script examples that can be used to obtain various types of data from the local computer.
How do I. | WMI classes or methods | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
. retrieve information about the Security event log? | Include the Security privilege when connecting to the Win32_NTEventlogFile class. For more information, see Executing Privileged Operations Using VBScript.
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
. back up an event log? | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
. back up an event log more than once? | Ensure that the backup file has a unique name before using the Win32_NTEventlogFile and the BackupEventLog method. The operating system does not allow you to overwrite an existing backup file; you must either move the backup file or rename it before you can run the script again. You may need to include the Backup privilege when connecting to WMI. For more information, see Executing Privileged Operations Using VBScript. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
. determine the number of records in an event log? | Use the Win32_NTEventlogFile class and check the value of the NumberOfRecords property. New-Event LogCreates a new event log and a new event source on a local or remote computer. SyntaxDescriptionThis cmdlet creates a new classic event log on a local or remote computer. It can also register an event source that writes to the new log or to an existing log. The cmdlets that contain the EventLog noun (the Event log cmdlets) work only on classic event logs. To get events from logs that use the Windows Event Log technology in Windows Vista and later versions of Windows, use Get-WinEvent . ExamplesExample 1 — create a new event logThis command creates the TestLog event log on the local computer and registers a new source for it. Example 2 — add a new event source to an existing logThis command adds a new event source, NewTestApp, to the Application log on the Server01 remote computer. The command requires that the NewTestApp.dll file is located on the Server01 computer. ParametersSpecifies the path to the file that contains category strings for the source events. This file is also known as the Category Message File. The file must be present on the computer on which the event log is being created. This parameter does not create or move files.
Creates the new event logs on the specified computers. The default is the local computer. The NetBIOS name, IP address, or fully qualified domain name of a remote computer. To specify the local computer, type the computer name, a dot (.), or «localhost». This parameter does not rely on PowerShell remoting. You can use the ComputerName parameter of Get-EventLog even if your computer is not configured to run remote commands.
Specifies the name of the event log. If the log does not exist, New-EventLog creates the log and uses this value for the Log and LogDisplayName properties of the new event log. If the log exists, New-EventLog registers a new source for the event log.
Specifies the path to the file that contains message formatting strings for the source events. This file is also known as the Event Message File. The file must be present on the computer on which the event log is being created. This parameter does not create or move files.
Specifies the path to the file that contains strings used for parameter substitutions in event descriptions. This file is also known as the Parameter Message File. The file must be present on the computer on which the event log is being created. This parameter does not create or move files.
Specifies the names of the event log sources, such as application programs that write to the event log. This parameter is required.
InputsNone You cannot pipe input to this cmdlet. OutputsNotesTo use New-EventLog on Windows Vista and later versions of Windows, open PowerShell with the «Run as administrator» option. To create an event source in Windows Vista, Windows XP Professional, or Windows Server 2003, you must be a member of the Administrators group on the computer. When you create a new event log and a new event source, the system registers the new source for the new log, but the log is not created until the first entry is written to it. The operating system stores event logs as files. When you create a new event log, the associated file is stored in the $env:SystemRoot\System32\Config directory on the specified computer. The file name is the first eight characters of the Log property with an .evt file name extension. Event Log КлассОпределениеОбеспечивает взаимодействие с журналами событий Windows. Provides interaction with Windows event logs. ПримерыВ следующем примере создается источник события MySource , если он еще не существует, и записывается запись в журнал событий MyNewLog . The following example creates the event source MySource if it doesn’t already exist, and writes an entry to the event log MyNewLog . Начиная с Windows Vista, это приложение необходимо запускать от имени администратора. Starting with Windows Vista, you must run this application as an administrator. КомментарииEventLog позволяет осуществлять доступ или настраивать журналы событий Windows, которые записывают сведения о важных событиях программного обеспечения или оборудования. EventLog lets you access or customize Windows event logs, which record information about important software or hardware events. С помощью EventLog можно выполнять чтение из существующих журналов, записывать записи в журналы, создавать или удалять источники событий, удалять журналы и отвечать на записи журнала. Using EventLog, you can read from existing logs, write entries to logs, create or delete event sources, delete logs, and respond to log entries. При создании источника событий можно также создать новые журналы. You can also create new logs when creating an event source. Этот тип реализует интерфейс IDisposable. This type implements the IDisposable interface. По окончании использования выдаленную ему память следует прямо или косвенно освободить. When you have finished using the type, you should dispose of it either directly or indirectly. Чтобы сделать это прямо, вызовите его метод Dispose в блоке try / catch . To dispose of the type directly, call its Dispose method in a try / catch block. Чтобы сделать это косвенно, используйте языковые конструкции, такие как using (в C#) или Using (в Visual Basic). To dispose of it indirectly, use a language construct such as using (in C#) or Using (in Visual Basic). Дополнительные сведения см. в разделе «Использование объекта, реализующего IDisposable» в статье об интерфейсе IDisposable. For more information, see the «Using an Object that Implements IDisposable» section in the IDisposable interface topic. Кроме предоставления доступа к отдельным журналам событий и их записям, EventLog класс позволяет получить доступ к коллекции всех журналов событий. In addition to providing access to individual event logs and their entries, the EventLog class lets you access the collection of all event logs. Члены класса можно использовать static EventLog для удаления журналов, получения списков журналов, создания или удаления источника, а также для определения того, содержит ли компьютер определенный источник. You can use the static members of EventLog to delete logs, get log lists, create or delete a source, or determine if a computer already contains a particular source. Существует три журнала событий по умолчанию: приложение, система и безопасность. There are three default event logs: Application, System, and Security. Журнал безопасности доступен только для чтения. A Security log is read-only. Другие приложения и службы, которые вы устанавливаете, например Active Directory, могут иметь дополнительные журналы событий. Other applications and services you install, such as Active Directory, might have additional event logs. При использовании класса необходимо учитывать вопросы безопасности EventLog . There are security considerations when using the EventLog class. EventLog требуются EventLogPermission разрешения для определенных действий в платформа .NET Framework 2,0 и более поздних версий или полное доверие в платформа .NET Framework 1,0 и 1,1. EventLog requires EventLogPermission permissions for specific actions in the .NET Framework 2.0 and later versions, or full trust in the .NET Framework 1.0 and 1.1. EventLogPermissionНе рекомендуется предоставлять частично доверенному коду. We recommend that EventLogPermission not be granted to partially trusted code. Никогда не следует передавать объекты журнала событий, включая EventLogEntryCollection и EventLogEntry , в менее надежный код. You should never pass any event log object, including EventLogEntryCollection and EventLogEntry objects, to less trusted code. Например, создание EventLog объекта, запись записи, а затем передача EventLog объекта в частично доверенный код может привести к возникновению проблемы безопасности, поскольку возможность чтения и записи в журнал событий позволяет коду выполнять такие действия, как выдача сообщений журнала событий в имени другого приложения. For example, creating an EventLog object, writing an entry, and then passing the EventLog object to partially trusted code can create a security issue, because the ability to read and write to the event log allows code to perform actions such as issuing event log messages in the name of another application. Начиная с Windows Vista, Управление учетными записями пользователей (UAC) определяет учетные данные пользователя. Starting with Windows Vista, User Account Control (UAC) determines the credentials of a user. Члену встроенной группы «Администраторы» присваивается два маркера доступа на время выполнения: маркер доступа обычного пользователя и маркер доступа администратора. If you are a member of the Built-in Administrators group, you are assigned two run-time access tokens: a standard user access token and an administrator access token. По умолчанию назначена роль обычного пользователя. By default, you are in the standard user role. Чтобы выполнить код, обращающийся к журналу безопасности, необходимо сначала повысить свои учетные данные от обычного пользователя до администратора. To run the code that accesses the Security log, you must first elevate your credentials from standard user to administrator. Это можно сделать при запуске приложения, открыв контекстное меню для приложения (если вы используете мышь, щелкните правой кнопкой мыши значок приложения) и укажите, что требуется запустить от имени администратора. You can do this when you start an application by opening the shortcut menu for the application (if you’re using a mouse, right-click the application icon) and indicating that you want to run as an administrator. Можно использовать EventLog для создания пользовательских журналов событий, которые можно просмотреть с помощью Просмотр событий сервера. You can use EventLog to create custom event logs that you can view through the server’s Event Viewer. Используйте RegisterDisplayName метод, чтобы отобразить локализованное имя для журнала событий в Просмотр событий. Use the RegisterDisplayName method to display a localized name for your event log in the Event Viewer. Используйте ModifyOverflowPolicy метод, чтобы настроить поведение журнала событий при достижении максимального размера журнала. Use the ModifyOverflowPolicy method to configure the behavior of your event log when it reaches its maximum log size. Для чтения из журнала событий укажите имя журнала ( Log свойство) и имя компьютера сервера ( MachineName свойство для журнала событий. To read from an event log, specify the log name (Log property) and server computer name (MachineName property for the event log. Если не указать имя компьютера сервера, предполагается, что используется локальный компьютер «.». If you don’t specify the server computer name, the local computer, «.», is assumed. Нет необходимости указывать источник события ( Source свойство), поскольку источник необходим только для записи в журналы. It’s not necessary to specify the event source (Source property), because a source is required only for writing to logs. EntriesСвойство автоматически заполняется списком записей журнала событий. The Entries property is automatically populated with the event log’s list of entries. Для записи в журнал событий укажите или создайте источник события ( Source свойство). To write to an event log, specify or create an event source (Source property). Для создания нового источника событий необходимо иметь учетные данные администратора на компьютере. You must have administrative credentials on the computer to create a new event source. Источник событий регистрирует приложение в журнале событий в качестве допустимого источника записей. The event source registers your application with the event log as a valid source of entries. Можно использовать источник событий для записи только в один журнал за раз. You can use the event source to write to only one log at a time. SourceСвойство может быть любой случайной строкой, но имя должно отличаться от других источников на компьютере. The Source property can be any random string, but the name must be distinct from other sources on the computer. Источником события обычно является имя приложения или другая идентифицирующая строка. The event source is typically the name of the application or another identifying string. При попытке создать повторяющееся Source значение возникает исключение. Trying to create a duplicate Source value throws an exception. Однако один журнал событий может быть связан с несколькими источниками. However, a single event log can be associated with multiple sources. Если источник событий для журнала событий, связанного с EventLog экземпляром, не существует, создается новый источник событий. If the event source for the event log associated with the EventLog instance doesn’t exist, a new event source is created. Чтобы создать источник событий в Windows Vista и более поздних версиях или Windows Server 2003, необходимо иметь учетные данные администратора. To create an event source in Windows Vista and later or Windows Server 2003, you must have administrative credentials. Это требование связано с тем, что необходимо выполнить поиск всех журналов событий, включая журналы безопасности, чтобы определить, является ли источник события уникальным. This requirement is because all event logs, including Security logs, must be searched to determine whether the event source is unique. Начиная с Windows Vista, пользователи не имеют разрешения на доступ к журналу безопасности; Поэтому SecurityException создается исключение. Starting with Windows Vista, users do not have permission to access the Security log; therefore, a SecurityException is thrown. Для создания или удаления источника события требуется синхронизация базового кода с помощью именованного мьютекса. Creating or deleting an event source requires synchronization of the underlying code by using a named mutex. Если приложение с высоким уровнем привилегий блокирует именованный мьютекс, попытка создать или удалить источник события приведет к тому, что приложение перестанет отвечать, пока блокировка не будет снята. If a highly privileged application locks the named mutex, trying to create or delete an event source causes the application to stop responding until the lock is released. Чтобы предотвратить возникновение этой проблемы, никогда не предоставляйте UnmanagedCode разрешение на ненадежный код. To help prevent this problem, never grant UnmanagedCode permission to untrusted code. Кроме того, UnmanagedCode разрешение, потенциально разрешающее обход других разрешений, может быть предоставлено только высоко доверенному коду. In addition, UnmanagedCode permission potentially allows other permissions to be bypassed and should only be granted to highly trusted code. Приложения и службы должны выполнять запись в журнал приложений или в пользовательский журнал. Applications and services should write to the Application log or to a custom log. Драйверы устройств должны записывать в системный журнал. Device drivers should write to the System log. Если свойство не задано явным образом Log , по умолчанию в журнале событий используется журнал приложений. If you do not explicitly set the Log property, the event log defaults to the Application log. Нет ничего защищать приложение от записи в качестве зарегистрированного источника. There is nothing to protect an application from writing as any registered source. Если приложению предоставлено Write разрешение, оно может записывать события для любого допустимого источника, зарегистрированного на компьютере. If an application is granted Write permission, it can write events for any valid source registered on the computer. Используйте WriteEvent методы и WriteEntry для записи событий в журнал событий. Use the WriteEvent and WriteEntry methods to write events to an event log. Для записи событий необходимо указать источник события. перед записью первой записи с источником необходимо создать и настроить источник события. You must specify an event source to write events; you must create and configure the event source before writing the first entry with the source. Создайте новый источник событий во время установки приложения. Create the new event source during the installation of your application. Это позволяет операционной системе обновлять свой список зарегистрированных источников событий и их конфигурацию. This allows time for the operating system to refresh its list of registered event sources and their configuration. Если операционная система не обновила список источников событий и вы пытаетесь написать событие с новым источником, операция записи завершится ошибкой. If the operating system hasn’t refreshed its list of event sources, and you try to write an event with the new source, the write operation will fail. Новый источник можно настроить с помощью EventLogInstaller объекта или CreateEventSource метода. You can configure a new source by using an EventLogInstaller object or the CreateEventSource method. Для создания нового источника событий необходимо иметь учетные данные администратора на компьютере. You must have administrative credentials on the computer to create a new event source. Каждый источник может записывать только один журнал событий; Однако приложение может использовать несколько источников для записи в несколько журналов событий. Each source can write to only one event log at a time; however, your application can use multiple sources to write to multiple event logs. Например, приложению может потребоваться несколько источников, настроенных для различных журналов событий или разных файлов ресурсов. For example, your application might require multiple sources configured for different event logs or different resource files. Чтобы изменить сведения о конфигурации существующего источника, необходимо удалить источник, а затем создать его с новой конфигурацией. To change the configuration details of an existing source, you must delete the source and then create it with the new configuration. Если другие приложения или компоненты используют существующий источник, создайте новый источник с обновленной конфигурацией вместо удаления существующего источника. If other applications or components use the existing source, create a new source with the updated configuration instead of deleting the existing source. Вы можете зарегистрировать источник событий в локализованных ресурсах для категории событий и строк сообщений. You can register the event source with localized resources for your event category and message strings. Приложение может записывать записи журнала событий с помощью идентификаторов ресурсов вместо указания фактических строковых значений. Your application can write event log entries by using resource identifiers instead of specifying the actual string values. EventLogInstaller EventSourceCreationData Дополнительные сведения о настройке источника с помощью файлов ресурсов см. в разделе классы и. Refer to the EventLogInstaller and EventSourceCreationData classes for more information about configuring your source with resource files. Если приложение записывает строковые значения непосредственно в журнал событий, не нужно задавать свойства файла ресурсов для источника. If your application writes string values directly to the event log, you do not have to set the resource file properties for the source. Источник должен быть настроен либо для записи локализованных записей, либо для записи прямых строк. The source must be configured either for writing localized entries or for writing direct strings. Если приложение записывает записи, используя как идентификаторы ресурсов, так и строковые значения, необходимо зарегистрировать два отдельных источника. If your application writes entries using both resource identifiers and string values, you must register two separate sources. Например, можно настроить один источник с файлами ресурсов, а затем использовать этот источник в WriteEvent методе для записи записей, использующих идентификаторы ресурсов, в журнал событий. For example, configure one source with resource files, and then use that source in the WriteEvent method to write entries using resource identifiers to the event log. Затем создайте другой источник без файлов ресурсов и используйте этот источник в WriteEntry методе для записи строк непосредственно в журнал событий с помощью этого источника. Then create a different source without resource files, and use that source in the WriteEntry method to write strings directly to the event log using that source. При записи событий необходимо по крайней мере указать либо строку сообщения, либо идентификатор ресурса для строки сообщения. When writing events, you must at least specify either a message string or the resource identifier for a message string. Другие свойства событий являются необязательными. Other event properties are optional. Примеры необязательных параметров событий включают следующее. Examples of optional event settings include the following: Можно задать, EventLogEntryType чтобы указать значок, отображаемый Просмотр событий для записи. You can set the EventLogEntryType to specify the icon that the Event Viewer displays for the entry. Можно указать идентификатор категории для события, если приложение использует категории для фильтрации событий. You can specify a category identifier for the event, if your application uses categories for filtering the events. Если требуется связать дополнительные сведения с заданным событием, можно присоединить двоичные данные к записи события. You can attach binary data to your event entry if you want to associate additional information with a given event. Ведение журнала событий потребляет место на диске, процессорное время и другие системные ресурсы. Event logging consumes disk space, processor time, and other system resources. Важно регистрировать только важную информацию. It is important to log only essential information. Рекомендуется размещать вызовы журнала событий в пути ошибки, а не в основном коде кода, чтобы они не влияли на производительность. We recommend that you place event log calls in an error path, rather than in the main code path, so they don’t adversely affect performance. Список начальных значений свойств для экземпляра EventLog см. в разделе EventLog конструктор. For a list of initial property values for an instance of EventLog, see the EventLog constructor. КонструкторыИнициализирует новый экземпляр класса EventLog. Initializes a new instance of the EventLog class. Не связывает экземпляр с каким-либо журналом. Does not associate the instance with any log. Инициализирует новый экземпляр класса EventLog. Initializes a new instance of the EventLog class. Связывает экземпляр с журналом на локальном компьютере. Associates the instance with a log on the local computer. Инициализирует новый экземпляр класса EventLog. Initializes a new instance of the EventLog class. Связывает экземпляр с журналом на указанном компьютере. Associates the instance with a log on the specified computer. Инициализирует новый экземпляр класса EventLog. Initializes a new instance of the EventLog class. Связывает экземпляр с журналом на указанном компьютере и создает или присваивает заданный источник классу EventLog. Associates the instance with a log on the specified computer and creates or assigns the specified source to the EventLog. СвойстваВозвращает значение, показывающее, может ли компонент вызывать событие. Gets a value indicating whether the component can raise an event. (Унаследовано от Component) | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Container | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
DesignMode | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
EnableRaisingEvents | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Log | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Source | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Delete(String) | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Dispose(Boolean) | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Exists(String) | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
GetLifetimeService() | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
GetService(Type) | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
GetType() | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
InitializeLifetimeService() | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
LogNameFromSourceName(String, String) | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
MemberwiseClone(Boolean) | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
ModifyOverflowPolicy(OverflowAction, Int32) | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
WriteEntry(String) | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
EntryWritten |