Windows event log provider

Windows Setup Log Files and Event Logs

Windows® Setup creates log files for all actions that occur during installation. If you are experiencing problems installing Windows, consult the log files to troubleshoot the installation.

WindowsВ Setup log files are available in the following directories:

Log location before Setup can access the drive.

Log location when Setup rolls back in the event of a fatal error.

Log location of Setup actions after disk configuration.

Used to log Plug and Play device installations.

Location of memory dump from bug checks.

Location of log minidumps from bug checks.

Location of Sysprep logs.

WindowsВ Setup Event Logs

WindowsВ Setup includes the ability to review the WindowsВ Setup performance events in the Windows Event Log viewer. This enables you to more easily review the actions that occurred during WindowsВ Setup and to review the performance statistics for different parts of WindowsВ Setup. You can filter the log so as to view only relevant items that you are interested in. The WindowsВ Setup performance events are saved into a log file that is named Setup.etl, which is available in the %WINDIR%\Panther directory of all installations. To view the logs, you must use the Event Viewer included with the Windows media that corresponds to the version of the customized image that you are building.

To view the logs on a computer that does not include the corresponding kit, you must run a script from the root of the media that installs the Event Trace for Windows (ETW) provider. From the command line, type:

where D is the drive letter of the Windows DVD media.

To view the WindowsВ Setup event logs

Start the Event Viewer, expand the Windows Logs node, and then click System.

In the Actions pane, click Open Saved Log and then locate the Setup.etl file. By default, this file is available in the %WINDIR%\Panther directory.

The log file contents appear in the Event Viewer.

To Export the log to a file

From the command line, use the Wevtutil or Tracerpt commands to save the log to an .xml or text file. For information about how to use these tools, see the command-line Help. The following commands show examples of how to use the tools:

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.

Logging providers in .NET

Logging providers persist logs, except for the Console provider, which only displays logs as standard output. For example, the Azure Application Insights provider stores logs in Azure Application Insights. Multiple providers can be enabled.

The default .NET Worker app templates:

The preceding code shows the Program class created with the .NET Worker app templates. The next several sections provide samples based on the .NET Worker app templates, which use the Generic Host.

To override the default set of logging providers added by Host.CreateDefaultBuilder , call ClearProviders and add the logging providers you want. For example, the following code:

  • Calls ClearProviders to remove all the ILoggerProvider instances from the builder.
  • Adds the Console logging provider.

For additional providers, see:

Configure a service that depends on ILogger

To configure a service that depends on ILogger , use constructor injection or provide a factory method. The factory method approach is recommended only if there is no other option. For example, consider a service that needs an ILogger instance provided by DI:

The preceding code is a Func that runs the first time the DI container needs to construct an instance of IExampleService . You can access any of the registered services in this way.

Built-in logging providers

Microsoft Extensions include the following logging providers as part of the runtime libraries:

The following logging providers are shipped by Microsoft, but not as part of the runtime libraries. They must be installed as additional NuGet packages.

Console

The Console provider logs output to the console.

Debug

The Debug provider writes log output by using the System.Diagnostics.Debug class. Calls to System.Diagnostics.Debug.WriteLine write to the Debug provider.

On Linux, the Debug provider log location is distribution-dependent and may be one of the following:

Event Source

The EventSource provider writes to a cross-platform event source with the name Microsoft-Extensions-Logging . On Windows, the provider uses ETW.

dotnet trace tooling

The dotnet-trace tool is a cross-platform CLI global tool that enables the collection of .NET Core traces of a running process. The tool collects Microsoft.Extensions.Logging.EventSource provider data using a LoggingEventSource.

See dotnet-trace for installation instructions. For a diagnostic tutorial using dotnet-trace , see Debug high CPU usage in .NET Core.

Windows EventLog

The EventLog provider sends log output to the Windows Event Log. Unlike the other providers, the EventLog provider does not inherit the default non-provider settings. If EventLog log settings aren’t specified, they default to LogLevel.Warning .

To log events lower than LogLevel.Warning, explicitly set the log level. The following example sets the Event Log default log level to LogLevel.Information:

AddEventLog overloads can pass in EventLogSettings. If null or not specified, the following default settings are used:

  • LogName : «Application»
  • SourceName : «.NET Runtime»
  • MachineName : The local machine name is used.

The following code changes the SourceName from the default value of «.NET Runtime» to CustomLogs :

Azure App Service

The Microsoft.Extensions.Logging.AzureAppServices provider package writes logs to text files in an Azure App Service app’s file system and to blob storage in an Azure Storage account.

The provider package isn’t included in the runtime libraries. To use the provider, add the provider package to the project.

To configure provider settings, use AzureFileLoggerOptions and AzureBlobLoggerOptions, as shown in the following example:

When deployed to Azure App Service, the app uses the settings in the App Service logs section of the App Service page of the Azure portal. When the following settings are updated, the changes take effect immediately without requiring a restart or redeployment of the app.

  • Application Logging (Filesystem)
  • Application Logging (Blob)

The default location for log files is in the D:\home\LogFiles\Application folder, and the default file name is diagnostics-yyyymmdd.txt. The default file size limit is 10 MB, and the default maximum number of files retained is 2. The default blob name is /yyyy/mm/dd/hh/-applicationLog.txt.

This provider only logs when the project runs in the Azure environment.

Azure log streaming

Azure log streaming supports viewing log activity in real time from:

  • The app server
  • The web server
  • Failed request tracing

To configure Azure log streaming:

  • Navigate to the App Service logs page from the app’s portal page.
  • Set Application Logging (Filesystem) to On.
  • Choose the log Level. This setting only applies to Azure log streaming.

Navigate to the Log Stream page to view logs. The logged messages are logged with the ILogger interface.

Azure Application Insights

The Microsoft.Extensions.Logging.ApplicationInsights provider package writes logs to Azure Application Insights. Application Insights is a service that monitors a web app and provides tools for querying and analyzing the telemetry data. If you use this provider, you can query and analyze your logs by using the Application Insights tools.

For more information, see the following resources:

Third-party logging providers

Here are some third-party logging frameworks that work with various .NET workloads:

Using a third-party framework is similar to using one of the built-in providers:

  1. Add a NuGet package to your project.
  2. Call an ILoggerFactory or ILoggingBuilder extension method provided by the logging framework.

For more information, see each provider’s documentation. Third-party logging providers aren’t supported by Microsoft.

Централизованный Event Log в Windows 2008 Server

Мне очень понравилась новая возможность по работе с журналами событий в Windows 2008/7/Vista, называемая Event Log forwarding (subscription — или подписка), которая основана на технологии WinRM. Данная функция позволяет вам получить все события со всех журналов с множества серверов без использования сторонних продуктов и настраивается все это в течении всего пары минут. Возможно, именно эта технология позволит вам отказаться от столь любимых многими системными администраторами Kiwi Syslog Viewer и Splunk.

Итак схема такая, у нас есть сервер Windows 2008, запущенный в качестве коллектора логов с одного или нескольких источников. В качестве подготовительной работы нужно выполнить следующие 3 шага:

На коллекторе логов в командной строке с правами администратора запустите следующую команду, которая запустит службу Windows Event Collector Service, измените тип ее запуска в автоматический (Automatically — Delayed Start) и включите канал ForwardedEvents, если он был отключен.
wecutil qc
На каждом из источников нужно активировать WinRM:
winrm quickconfig
По умолчанию сервер-коллектор логов не может просто собирать информацию из журналов событий источников, вам придется добавить учетную запись компьютера-коллектора в локальные администраторы на все сервера-источники логов (в том случае, если сервер-источник работает под управлением 2008 R2, то достаточно добавить учетку коллектора в группу Event Log Readers)

Теперь мы должны создать подписки (Subscriptions) на сервер коллектор. Для чего зайдите на него, откройте консоль MMC Event Viewer, щелкните правой кнопкой мыши по Subscriptions и выберите Create Subscription:

Здесь вы можете выбрать несколько различных настроек.

При каждом добавлении коллектора, неплохо было бы проверить подключение:

Далее вы должны настроить фильтр, указав какие типы событий вы хотите получать (например, Errors и Warnings), также можно собирать события по конкретным номерам Event ID или по словам в описании события. Есть один нюанс: не выбирайте слишком много типов событий в одну подписку, анализировать этот журнал можно будет бесконечно :).

Расширенные настройки (Advanced settings) могут понадобиться, если вы хотите использовать нестандартный порт для WinRM, или захотите работать по протоколу HTTPS, или же оптимизировать сьор логов по медленным каналам WAN.

После нажатия OK подписка будет создана. Здесь вы можете щелкнуть правой кнопкой мыши по подписке и получить статус выполнения (Runtime Status), или перезапустить ее (Retry) если предыдущий запуск был неудачным. Обратите внимание, что даже если ваша подписка имеет зеленый значок, в процедуре сбора логов могут быть ошибки. Поэтому всегда проверяйте Runtime Status.

После начала работы подписки, вы сможете просматривать перенаправленные события. Имейте в виду, что если журналы очень большие, то их первичный сбор может занять некоторое время.

Конфигурацию можно посмотреть на вкладке Properties -> Subscriptions.

В том случае, если сбор логов не работает, сначала на сервере-источнике логов удостоверьтесь, что локальный файрвол настроен корректно и разрешает трафик WinRM.

Один раз, когда я добавил учетную запись сервера-коллектора в группу Event Log Readers, но не добавил ее локальные админы, была такая ошибка;

[WDS1.ad.local] – Error – Last retry time: 2010-09-28 16:46:22. Code (0×5): Windows Event Forward Plugin failed to read events. Next retry time: 2010-09-28 16:51:22.

Я попробовал добавить учетку сервера в группу локальных админов, в результате появилась такая ошибка:

[WDS1.ad.local] – Error – Last retry time: 2010-09-28 16:43:18. Code (0×7A): The data area passed to a system call is too small. Next retry time: 2010-09-28 16:48:18.

Оказывается, я выбрал в фильтре слишком много журналов для сбора. Поправив фильтры так, чтобы они собирали чуть меньше информации, я победил эту ошибку.

Читайте также:  Windows 10 logon changerlogin background changer
Оцените статью
Log file location Description