setx command structure (#24421)

pull/24432/head
Luke Latham 2021-12-27 17:21:24 -06:00 committed by GitHub
parent 62d6ae5bc9
commit 181a59767d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 120 additions and 120 deletions

View File

@ -34,7 +34,7 @@ The default ASP.NET Core web app templates:
[!code-csharp[](index/samples/6.x/WebApp/Program.cs?name=snippet1&highlight=1)]
The preceding code shows the *Program.cs* file created with the ASP.NET Core web app templates. The next several sections provide samples based on the ASP.NET Core web app templates, which use the Generic Host.
The preceding code shows the `Program.cs` file created with the ASP.NET Core web app templates. The next several sections provide samples based on the ASP.NET Core web app templates, which use the Generic Host.
The following code overrides the default set of logging providers added by `WebApplication.CreateBuilder`:
@ -51,7 +51,7 @@ For additional providers, see:
## Create logs
To create logs, use an <xref:Microsoft.Extensions.Logging.ILogger%601> object from [dependency injection](xref:fundamentals/dependency-injection) (DI).
To create logs, use an <xref:Microsoft.Extensions.Logging.ILogger%601> object from [dependency injection (DI)](xref:fundamentals/dependency-injection).
The following example:
@ -66,7 +66,7 @@ For information on Blazor, see <xref:blazor/fundamentals/logging>.
## Configure logging
Logging configuration is commonly provided by the `Logging` section of *appsettings*.`{Environment}`*.json* files. The following *appsettings.Development.json* file is generated by the ASP.NET Core web app templates:
Logging configuration is commonly provided by the `Logging` section of `appsettings.{ENVIRONMENT}.json` files, where the `{ENVIRONMENT}` placeholder is the [environment](xref:fundamentals/environments). The following `appsettings.Development.json` file is generated by the ASP.NET Core web app templates:
[!code-json[](index/samples/6.x/TodoApiDTO/appsettings.Development.json)]
@ -83,19 +83,19 @@ The `Logging` property can have <xref:Microsoft.Extensions.Logging.LogLevel> and
When a `LogLevel` is specified, logging is enabled for messages at the specified level and higher. In the preceding JSON, the `Default` category is logged for `Information` and higher. For example, `Information`, `Warning`, `Error`, and `Critical` messages are logged. If no `LogLevel` is specified, logging defaults to the `Information` level. For more information, see [Log levels](#llvl).
A provider property can specify a `LogLevel` property. `LogLevel` under a provider specifies levels to log for that provider, and overrides the non-provider log settings. Consider the following *appsettings.json* file:
A provider property can specify a `LogLevel` property. `LogLevel` under a provider specifies levels to log for that provider, and overrides the non-provider log settings. Consider the following `appsettings.json` file:
[!code-json[](index/samples/3.x/TodoApiDTO/appsettings.Prod2.json)]
Settings in `Logging.{providername}.LogLevel` override settings in `Logging.LogLevel`. In the preceding JSON, the `Debug` provider's default log level is set to `Information`:
Settings in `Logging.{PROVIDER NAME}.LogLevel` override settings in `Logging.LogLevel`, where the `{PROVIDER NAME}` placeholder is the provider name. In the preceding JSON, the `Debug` provider's default log level is set to `Information`:
`Logging:Debug:LogLevel:Default:Information`
The preceding setting specifies the `Information` log level for every `Logging:Debug:` category except `Microsoft.Hosting`. When a specific category is listed, the specific category overrides the default category. In the preceding JSON, the `Logging:Debug:LogLevel` categories `"Microsoft.Hosting"` and `"Default"` override the settings in `Logging:LogLevel`
The preceding setting specifies the `Information` log level for every `Logging:Debug:` category except `Microsoft.Hosting`. When a specific category is listed, the specific category overrides the default category. In the preceding JSON, the `Logging:Debug:LogLevel` categories `"Microsoft.Hosting"` and `"Default"` override the settings in `Logging:LogLevel`.
The minimum log level can be specified for any of:
* Specific providers: For example, `Logging:EventSource:LogLevel:Default:Information`
* Specific providers: For example, `Logging:EventSource:LogLevel:Default:Information`
* Specific categories: For example, `Logging:LogLevel:Microsoft:Warning`
* All providers and all categories: `Logging:LogLevel:Default:Warning`
@ -104,26 +104,26 @@ Any logs below the minimum level are ***not***:
* Passed to the provider.
* Logged or displayed.
To suppress all logs, specify [LogLevel.None](xref:Microsoft.Extensions.Logging.LogLevel). `LogLevel.None` has a value of 6, which is higher than `LogLevel.Critical` (5).
To suppress all logs, specify <xref:Microsoft.Extensions.Logging.LogLevel.None?displayProperty=nameWithType>. `LogLevel.None` has a value of 6, which is higher than `LogLevel.Critical` (5).
If a provider supports [log scopes](#logscopes), `IncludeScopes` indicates whether they're enabled. For more information, see [log scopes](#logscopes)
If a provider supports [log scopes](#logscopes), `IncludeScopes` indicates whether they're enabled. For more information, see [log scopes](#logscopes).
The following *appsettings.json* file contains all the providers enabled by default:
The following `appsettings.json` file contains all the providers enabled by default:
[!code-json[](index/samples/3.x/TodoApiDTO/appsettings.Production.json)]
In the preceding sample:
* The categories and levels are not suggested values. The sample is provided to show all the default providers.
* Settings in `Logging.{providername}.LogLevel` override settings in `Logging.LogLevel`. For example, the level in `Debug.LogLevel.Default` overrides the level in `LogLevel.Default`.
* Settings in `Logging.{PROVIDER NAME}.LogLevel` override settings in `Logging.LogLevel`, where the `{PROVIDER NAME}` placeholder is the provider name. For example, the level in `Debug.LogLevel.Default` overrides the level in `LogLevel.Default`.
* Each default provider *alias* is used. Each provider defines an *alias* that can be used in configuration in place of the fully qualified type name. The built-in providers aliases are:
* Console
* Debug
* EventSource
* EventLog
* AzureAppServicesFile
* AzureAppServicesBlob
* ApplicationInsights
* `Console`
* `Debug`
* `EventSource`
* `EventLog`
* `AzureAppServicesFile`
* `AzureAppServicesBlob`
* `ApplicationInsights`
## Set log level by command line, environment variables, and other configuration
@ -136,7 +136,7 @@ The following commands:
* Set the environment key `Logging:LogLevel:Microsoft` to a value of `Information` on Windows.
* Test the settings when using an app created with the ASP.NET Core web application templates. The `dotnet run` command must be run in the project directory after using `set`.
```cmd
```dotnetcli
set Logging__LogLevel__Microsoft=Information
dotnet run
```
@ -148,26 +148,26 @@ The preceding environment setting:
The following [setx](/windows-server/administration/windows-commands/setx) command also sets the environment key and value on Windows. Unlike `set`, `setx` settings are persisted. The `/M` switch sets the variable in the system environment. If `/M` isn't used, a user environment variable is set.
```cmd
setx Logging__LogLevel__Microsoft=Information /M
```console
setx Logging__LogLevel__Microsoft Information /M
```
Consider the following *appsettings.json* file:
Consider the following `appsettings.json` file:
```json
"Logging": {
"Console": {
"LogLevel": {
"Microsoft.Hosting.Lifetime": "Trace"
}
"Console": {
"LogLevel": {
"Microsoft.Hosting.Lifetime": "Trace"
}
}
}
```
The following command sets the preceding configuration in the environment:
```cmd
setx Logging__Console__LogLevel__Microsoft.Hosting.Lifetime=Trace /M
```console
setx Logging__Console__LogLevel__Microsoft.Hosting.Lifetime Trace /M
```
On [Azure App Service](https://azure.microsoft.com/services/app-service/), select **New application setting** on the **Settings > Configuration** page. Azure App Service application settings are:
@ -227,17 +227,17 @@ The following table lists the <xref:Microsoft.Extensions.Logging.LogLevel> value
| LogLevel | Value | Method | Description |
| -------- | ----- | ------ | ----------- |
| [Trace](xref:Microsoft.Extensions.Logging.LogLevel) | 0 | <xref:Microsoft.Extensions.Logging.LoggerExtensions.LogTrace%2A> | Contain the most detailed messages. These messages may contain sensitive app data. These messages are disabled by default and should ***not*** be enabled in production. |
| [Debug](xref:Microsoft.Extensions.Logging.LogLevel) | 1 | <xref:Microsoft.Extensions.Logging.LoggerExtensions.LogDebug%2A> | For debugging and development. Use with caution in production due to the high volume. |
| [Information](xref:Microsoft.Extensions.Logging.LogLevel) | 2 | <xref:Microsoft.Extensions.Logging.LoggerExtensions.LogInformation%2A> | Tracks the general flow of the app. May have long-term value. |
| [Warning](xref:Microsoft.Extensions.Logging.LogLevel) | 3 | <xref:Microsoft.Extensions.Logging.LoggerExtensions.LogWarning%2A> | For abnormal or unexpected events. Typically includes errors or conditions that don't cause the app to fail. |
| [Error](xref:Microsoft.Extensions.Logging.LogLevel) | 4 | <xref:Microsoft.Extensions.Logging.LoggerExtensions.LogError%2A> | For errors and exceptions that cannot be handled. These messages indicate a failure in the current operation or request, not an app-wide failure. |
| [Critical](xref:Microsoft.Extensions.Logging.LogLevel) | 5 | <xref:Microsoft.Extensions.Logging.LoggerExtensions.LogCritical%2A> | For failures that require immediate attention. Examples: data loss scenarios, out of disk space. |
| [None](xref:Microsoft.Extensions.Logging.LogLevel) | 6 | | Specifies that a logging category should not write any messages. |
| <xref:Microsoft.Extensions.Logging.LogLevel.Trace> | 0 | <xref:Microsoft.Extensions.Logging.LoggerExtensions.LogTrace%2A> | Contain the most detailed messages. These messages may contain sensitive app data. These messages are disabled by default and should ***not*** be enabled in production. |
| <xref:Microsoft.Extensions.Logging.LogLevel.Debug> | 1 | <xref:Microsoft.Extensions.Logging.LoggerExtensions.LogDebug%2A> | For debugging and development. Use with caution in production due to the high volume. |
| <xref:Microsoft.Extensions.Logging.LogLevel.Information> | 2 | <xref:Microsoft.Extensions.Logging.LoggerExtensions.LogInformation%2A> | Tracks the general flow of the app. May have long-term value. |
| <xref:Microsoft.Extensions.Logging.LogLevel.Warning> | 3 | <xref:Microsoft.Extensions.Logging.LoggerExtensions.LogWarning%2A> | For abnormal or unexpected events. Typically includes errors or conditions that don't cause the app to fail. |
| <xref:Microsoft.Extensions.Logging.LogLevel.Error> | 4 | <xref:Microsoft.Extensions.Logging.LoggerExtensions.LogError%2A> | For errors and exceptions that cannot be handled. These messages indicate a failure in the current operation or request, not an app-wide failure. |
| <xref:Microsoft.Extensions.Logging.LogLevel.Critical> | 5 | <xref:Microsoft.Extensions.Logging.LoggerExtensions.LogCritical%2A> | For failures that require immediate attention. Examples: data loss scenarios, out of disk space. |
| <xref:Microsoft.Extensions.Logging.LogLevel.None> | 6 | | Specifies that a logging category shouldn't write messages. |
In the previous table, the `LogLevel` is listed from lowest to highest severity.
The [Log](xref:Microsoft.Extensions.Logging.LoggerExtensions) method's first parameter, <xref:Microsoft.Extensions.Logging.LogLevel>, indicates the severity of the log. Rather than calling `Log(LogLevel, ...)`, most developers call the [Log{LogLevel}](xref:Microsoft.Extensions.Logging.LoggerExtensions) extension methods. The `Log{LogLevel}` extension methods [call the Log method and specify the LogLevel](https://github.com/dotnet/extensions/blob/release/3.1/src/Logging/Logging.Abstractions/src/LoggerExtensions.cs). For example, the following two logging calls are functionally equivalent and produce the same log:
The <xref:Microsoft.Extensions.Logging.LoggerExtensions.Log%2A> method's first parameter, <xref:Microsoft.Extensions.Logging.LogLevel>, indicates the severity of the log. Rather than calling `Log(LogLevel, ...)`, most developers call the [`Log{LOG LEVEL}`](xref:Microsoft.Extensions.Logging.LoggerExtensions) extension methods, where the `{LOG LEVEL}` placeholder is the log level. For example, the following two logging calls are functionally equivalent and produce the same log:
[!code-csharp[](index/samples/3.x/TodoApiDTO/Controllers/TestController.cs?name=snippet0&highlight=6-7)]
@ -249,9 +249,9 @@ The following code creates `Information` and `Warning` logs:
[!code-csharp[](index/samples/3.x/TodoApiDTO/Controllers/TodoItemsController.cs?name=snippet_CallLogMethods&highlight=4,10)]
In the preceding code, the first `Log{LogLevel}` parameter,`MyLogEvents.GetItem`, is the [Log event ID](#leid). The second parameter is a message template with placeholders for argument values provided by the remaining method parameters. The method parameters are explained in the [message template](#lmt) section later in this document.
In the preceding code, the first `Log{LOG LEVEL}` parameter,`MyLogEvents.GetItem`, is the [Log event ID](#leid). The second parameter is a message template with placeholders for argument values provided by the remaining method parameters. The method parameters are explained in the [message template](#lmt) section later in this document.
Call the appropriate `Log{LogLevel}` method to control how much log output is written to a particular storage medium. For example:
Call the appropriate `Log{LOG LEVEL}` method to control how much log output is written to a particular storage medium. For example:
* In production:
* Logging at the `Trace` or `Information` levels produces a high-volume of detailed log messages. To control costs and not exceed data storage limits, log `Trace` and `Information` level messages to a high-volume, low-cost data store. Consider limiting `Trace` and `Information` to specific categories.
@ -265,7 +265,7 @@ Call the appropriate `Log{LogLevel}` method to control how much log output is wr
ASP.NET Core writes logs for framework events. For example, consider the log output for:
* A Razor Pages app created with the ASP.NET Core templates.
* Logging set to `Logging:Console:LogLevel:Microsoft:Information`
* Logging set to `Logging:Console:LogLevel:Microsoft:Information`.
* Navigation to the Privacy page:
```console
@ -371,9 +371,9 @@ If the default log level is not set, the default log level value is `Information
For example, consider the following web app:
* Created with the ASP.NET web app templates.
* *appsettings.json* and *appsettings.Development.json* deleted or renamed.
* `appsettings.json` and `appsettings.Development.json` deleted or renamed.
With the preceding setup, navigating to the privacy or home page produces many `Trace`, `Debug`, and `Information` messages with `Microsoft` in the category name.
With the preceding setup, navigating to the privacy or home page produces many `Trace`, `Debug`, and `Information` messages with `Microsoft` in the category name.
The following code sets the default log level when the default log level is not set in configuration:
@ -395,19 +395,19 @@ Generally, log levels should be specified in configuration and not code.
The following table contains some categories used by ASP.NET Core and Entity Framework Core, with notes about the logs:
| Category | Notes |
| ----------------------------------- | ----- |
| Microsoft.AspNetCore | General ASP.NET Core diagnostics. |
| Microsoft.AspNetCore.DataProtection | Which keys were considered, found, and used. |
| Microsoft.AspNetCore.HostFiltering | Hosts allowed. |
| Microsoft.AspNetCore.Hosting | How long HTTP requests took to complete and what time they started. Which hosting startup assemblies were loaded. |
| Microsoft.AspNetCore.Mvc | MVC and Razor diagnostics. Model binding, filter execution, view compilation, action selection. |
| Microsoft.AspNetCore.Routing | Route matching information. |
| Microsoft.AspNetCore.Server | Connection start, stop, and keep alive responses. HTTPS certificate information. |
| Microsoft.AspNetCore.StaticFiles | Files served. |
| Microsoft.EntityFrameworkCore | General Entity Framework Core diagnostics. Database activity and configuration, change detection, migrations. |
| Category | Notes |
| ------------------------------------- | ----- |
| `Microsoft.AspNetCore` | General ASP.NET Core diagnostics. |
| `Microsoft.AspNetCore.DataProtection` | Which keys were considered, found, and used. |
| `Microsoft.AspNetCore.HostFiltering` | Hosts allowed. |
| `Microsoft.AspNetCore.Hosting` | How long HTTP requests took to complete and what time they started. Which hosting startup assemblies were loaded. |
| `Microsoft.AspNetCore.Mvc` | MVC and Razor diagnostics. Model binding, filter execution, view compilation, action selection. |
| `Microsoft.AspNetCore.Routing` | Route matching information. |
| `Microsoft.AspNetCore.Server` | Connection start, stop, and keep alive responses. HTTPS certificate information. |
| `Microsoft.AspNetCore.StaticFiles` | Files served. |
| `Microsoft.EntityFrameworkCore` | General Entity Framework Core diagnostics. Database activity and configuration, change detection, migrations. |
To view more categories in the console window, set **appsettings.Development.json** to the following:
To view more categories in the console window, set **`appsettings.Development.json`** to the following:
[!code-json[](index/samples/3.x/MyMain/appsettings.Trace.json)]
@ -421,13 +421,13 @@ To view more categories in the console window, set **appsettings.Development.jso
A scope:
* Is an <xref:System.IDisposable> type that's returned by the <xref:Microsoft.Extensions.Logging.ILogger.BeginScope*> method.
* Is an <xref:System.IDisposable> type that's returned by the <xref:Microsoft.Extensions.Logging.ILogger.BeginScope%2A> method.
* Lasts until it's disposed.
The following providers support scopes:
* `Console`
* [AzureAppServicesFile and AzureAppServicesBlob](xref:Microsoft.Extensions.Logging.AzureAppServices.BatchingLoggerOptions.IncludeScopes)
* [`AzureAppServicesFile` and `AzureAppServicesBlob`](xref:Microsoft.Extensions.Logging.AzureAppServices.BatchingLoggerOptions.IncludeScopes)
Use a scope by wrapping logger calls in a `using` block:
@ -439,16 +439,16 @@ Use a scope by wrapping logger calls in a `using` block:
ASP.NET Core includes the following logging providers as part of the shared framework:
* [Console](#console)
* [Debug](#debug)
* [EventSource](#event-source)
* [EventLog](#welog)
* [`Console`](#console)
* [`Debug`](#debug)
* [`EventSource`](#event-source)
* [`EventLog`](#welog)
The following logging providers are shipped by Microsoft, but not as part of the
shared framework. They must be installed as additional nuget.
* [AzureAppServicesFile and AzureAppServicesBlob](#azure-app-service)
* [ApplicationInsights](#azure-application-insights)
* [`AzureAppServicesFile` and `AzureAppServicesBlob`](#azure-app-service)
* [`ApplicationInsights`](#azure-application-insights)
ASP.NET Core doesn't include a logging provider for writing logs to files. To write logs to files from an ASP.NET Core app, consider using a [third-party logging provider](#third-party-logging-providers).
@ -464,8 +464,8 @@ The `Debug` provider writes log output by using the [System.Diagnostics.Debug](/
On Linux, the `Debug` provider log location is distribution-dependent and may be one of the following:
* */var/log/message*
* */var/log/syslog*
* `/var/log/message`
* `/var/log/syslog`
### Event Source
@ -473,11 +473,11 @@ The `EventSource` provider writes to a cross-platform event source with the name
#### dotnet trace tooling
The [dotnet-trace](/dotnet/core/diagnostics/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 <xref:Microsoft.Extensions.Logging.EventSource> provider data using a <xref:Microsoft.Extensions.Logging.EventSource.LoggingEventSource>.
The [`dotnet-trace`](/dotnet/core/diagnostics/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 <xref:Microsoft.Extensions.Logging.EventSource> provider data using a <xref:Microsoft.Extensions.Logging.EventSource.LoggingEventSource>.
See [dotnet-trace](/dotnet/core/diagnostics/dotnet-trace) for installation instructions.
For installation instructions, see [`dotnet-trace`](/dotnet/core/diagnostics/dotnet-trace).
Use the dotnet trace tooling to collect a trace from an app:
Use the `dotnet trace` tooling to collect a trace from an app:
1. Run the app with the `dotnet run` command.
1. Determine the process identifier (PID) of the .NET Core app:
@ -528,24 +528,24 @@ Use the dotnet trace tooling to collect a trace from an app:
The following table lists the provider levels:
| Provider Level | Description |
| :---------: | --------------- |
| 0 | `LogAlways` |
| 1 | `Critical` |
| 2 | `Error` |
| 3 | `Warning` |
| 4 | `Informational` |
| 5 | `Verbose` |
| :------------: | --------------- |
| 0 | `LogAlways` |
| 1 | `Critical` |
| 2 | `Error` |
| 3 | `Warning` |
| 4 | `Informational` |
| 5 | `Verbose` |
The parsing for a category level can be either a string or a number:
| Category named value | Numeric value |
| :-----: | ----------- |
| `Trace` | 0 |
| `Debug` | 1 |
| `Information` | 2 |
| `Warning` | 3 |
| `Error` | 4 |
| `Critical` | 5 |
| Category named value | Numeric value |
| :------------------: | ------------- |
| `Trace` | 0 |
| `Debug` | 1 |
| `Information` | 2 |
| `Warning` | 3 |
| `Error` | 4 |
| `Critical` | 5 |
The provider level and category level:
@ -554,13 +554,13 @@ Use the dotnet trace tooling to collect a trace from an app:
If no `FilterSpecs` are specified then the `EventSourceLogger` implementation attempts to convert the provider level to a category level and applies it to all categories.
| Provider Level | Category Level |
| :-----: | ----------- |
| `Verbose`(5) | `Debug`(1) |
| `Informational`(4) | `Information`(2) |
| `Warning`(3) | `Warning`(3) |
| `Error`(2) | `Error`(4) |
| `Critical`(1) | `Critical`(5) |
| Provider Level | Category Level |
| :----------------: | ---------------- |
| `Verbose`(5) | `Debug`(1) |
| `Informational`(4) | `Information`(2) |
| `Warning`(3) | `Warning`(3) |
| `Error`(2) | `Error`(4) |
| `Critical`(1) | `Critical`(5) |
If `FilterSpecs` are provided, any category that is included in the list uses the category level encoded there, all other categories are filtered out.
@ -617,21 +617,20 @@ Use the dotnet trace tooling to collect a trace from an app:
* The Event Source logger to produce formatted strings (`4`) for errors (`2`).
* `Microsoft.AspNetCore.Hosting` logging at the `Informational` logging level (`4`).
1. Stop the dotnet trace tooling by pressing the Enter key or Ctrl+C.
1. Stop the dotnet trace tooling by pressing the Enter key or <kbd>Ctrl</kbd>+<kbd>C</kbd>.
The trace is saved with the name *trace.nettrace* in the folder where the `dotnet trace` command is executed.
The trace is saved with the name `trace.nettrace` in the folder where the `dotnet trace` command is executed.
1. Open the trace with [Perfview](#perfview). Open the *trace.nettrace* file and explore the trace events.
1. Open the trace with [Perfview](#perfview). Open the `trace.nettrace` file and explore the trace events.
If the app doesn't build the host with `CreateDefaultBuilder`, add the Event Source provider to the app's logging configuration.
For more information, see:
* [Trace for performance analysis utility (dotnet-trace)](/dotnet/core/diagnostics/dotnet-trace) (.NET Core documentation)
* [Trace for performance analysis utility (dotnet-trace)](https://github.com/dotnet/diagnostics/blob/main/documentation/dotnet-trace-instructions.md) (dotnet/diagnostics GitHub repository documentation)
* [LoggingEventSource Class](xref:Microsoft.Extensions.Logging.EventSource.LoggingEventSource) (.NET API Browser)
* [Trace for performance analysis utility (`dotnet-trace`)](/dotnet/core/diagnostics/dotnet-trace) (.NET Core documentation)
* [Trace for performance analysis utility (`dotnet-trace`)](https://github.com/dotnet/diagnostics/blob/main/documentation/dotnet-trace-instructions.md) (dotnet/diagnostics GitHub repository documentation)
* <xref:Microsoft.Extensions.Logging.EventSource.LoggingEventSource>
* <xref:System.Diagnostics.Tracing.EventLevel>
* [LoggingEventSource reference source (3.0)](https://github.com/dotnet/extensions/blob/release/3.1/src/Logging/Logging.EventSource/src/LoggingEventSource.cs): To obtain reference source for a different version, change the branch to `release/{Version}`, where `{Version}` is the version of ASP.NET Core desired.
* [Perfview](#perfview): Useful for viewing Event Source traces.
#### Perfview
@ -644,7 +643,7 @@ To configure PerfView for collecting events logged by this provider, add the str
### 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](https://github.com/dotnet/extensions/blob/release/3.1/src/Hosting/Hosting/src/Host.cs#L99-L103).
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 <xref:Microsoft.Extensions.Logging.LogLevel.Warning?displayProperty=nameWithType>.
To log events lower than <xref:Microsoft.Extensions.Logging.LogLevel.Warning?displayProperty=nameWithType>, explicitly set the log level. The following example sets the Event Log default log level to <xref:Microsoft.Extensions.Logging.LogLevel.Information?displayProperty=nameWithType>:
@ -658,7 +657,7 @@ To log events lower than <xref:Microsoft.Extensions.Logging.LogLevel.Warning?dis
}
```
[AddEventLog overloads](xref:Microsoft.Extensions.Logging.EventLoggerFactoryExtensions) can pass in <xref:Microsoft.Extensions.Logging.EventLog.EventLogSettings>. If `null` or not specified, the following default settings are used:
<xref:Microsoft.Extensions.Logging.EventLoggerFactoryExtensions.AddEventLog%2A> overloads can pass in <xref:Microsoft.Extensions.Logging.EventLog.EventLogSettings>. If `null` or not specified, the following default settings are used:
* `LogName`: "Application"
* `SourceName`: ".NET Runtime"
@ -670,7 +669,7 @@ The following code changes the `SourceName` from the default value of `".NET Run
### Azure App Service
The [Microsoft.Extensions.Logging.AzureAppServices](https://www.nuget.org/packages/Microsoft.Extensions.Logging.AzureAppServices) provider package writes logs to text files in an Azure App Service app's file system and to [blob storage](/azure/storage/blobs/storage-quickstart-blobs-dotnet#what-is-blob-storage) in an Azure Storage account.
The [`Microsoft.Extensions.Logging.AzureAppServices`](https://www.nuget.org/packages/Microsoft.Extensions.Logging.AzureAppServices) provider package writes logs to text files in an Azure App Service app's file system and to [blob storage](/azure/storage/blobs/storage-quickstart-blobs-dotnet#what-is-blob-storage) in an Azure Storage account.
The provider package isn't included in the shared framework. To use the provider, add the provider package to the project.
@ -683,7 +682,7 @@ When deployed to Azure App Service, the app uses the settings in the [App Servic
* **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 *{app-name}{timestamp}/yyyy/mm/dd/hh/{guid}-applicationLog.txt*.
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 `{app-name}{timestamp}/yyyy/mm/dd/hh/{guid}-applicationLog.txt`.
This provider only logs when the project runs in the Azure environment.
@ -705,19 +704,19 @@ Navigate to the **Log Stream** page to view logs. The logged messages are logged
### Azure Application Insights
The [Microsoft.Extensions.Logging.ApplicationInsights](https://www.nuget.org/packages/Microsoft.Extensions.Logging.ApplicationInsights) provider package writes logs to [Azure Application Insights](/azure/azure-monitor/app/cloudservices). 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.
The [`Microsoft.Extensions.Logging.ApplicationInsights`](https://www.nuget.org/packages/Microsoft.Extensions.Logging.ApplicationInsights) provider package writes logs to [Azure Application Insights](/azure/azure-monitor/app/cloudservices). 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.
The logging provider is included as a dependency of [Microsoft.ApplicationInsights.AspNetCore](https://www.nuget.org/packages/Microsoft.ApplicationInsights.AspNetCore), which is the package that provides all available telemetry for ASP.NET Core. If you use this package, you don't have to install the provider package.
The logging provider is included as a dependency of [`Microsoft.ApplicationInsights.AspNetCore`](https://www.nuget.org/packages/Microsoft.ApplicationInsights.AspNetCore), which is the package that provides all available telemetry for ASP.NET Core. If you use this package, you don't have to install the provider package.
The [Microsoft.ApplicationInsights.Web](https://www.nuget.org/packages/Microsoft.ApplicationInsights.Web) package is for ASP.NET 4.x, not ASP.NET Core.
The [`Microsoft.ApplicationInsights.Web`](https://www.nuget.org/packages/Microsoft.ApplicationInsights.Web) package is for ASP.NET 4.x, not ASP.NET Core.
For more information, see the following resources:
* [Application Insights overview](/azure/application-insights/app-insights-overview)
* [Application Insights for ASP.NET Core applications](/azure/azure-monitor/app/asp-net-core) - Start here if you want to implement the full range of Application Insights telemetry along with logging.
* [ApplicationInsightsLoggerProvider for .NET Core ILogger logs](/azure/azure-monitor/app/ilogger) - Start here if you want to implement the logging provider without the rest of Application Insights telemetry.
* [Application Insights logging adapters](/azure/azure-monitor/app/asp-net-trace-logs).
* [Install, configure, and initialize the Application Insights SDK](/learn/modules/instrument-web-app-code-with-application-insights) - Interactive tutorial on the Microsoft Learn site.
* [Application Insights for ASP.NET Core applications](/azure/azure-monitor/app/asp-net-core): Start here if you want to implement the full range of Application Insights telemetry along with logging.
* [ApplicationInsightsLoggerProvider for .NET Core ILogger logs](/azure/azure-monitor/app/ilogger): Start here if you want to implement the logging provider without the rest of Application Insights telemetry.
* [Application Insights logging adapters](/azure/azure-monitor/app/asp-net-trace-logs)
* [Install, configure, and initialize the Application Insights SDK](/learn/modules/instrument-web-app-code-with-application-insights): Interactive tutorial on the Microsoft Learn site.
## Third-party logging providers
@ -815,31 +814,31 @@ public class Program
## Configure a service that depends on ILogger
Constructor injection of a logger into `Startup` works in earlier versions of ASP.NET Core because a separate DI container is created for the Web Host. For information about why only one container is created for the Generic Host, see the [breaking change announcement](https://github.com/aspnet/Announcements/issues/353).
Constructor injection of a logger into `Startup` works in earlier versions of ASP.NET Core because a separate dependency injection (DI) container is created for the Web Host. For information about why only one container is created for the Generic Host, see the [breaking change announcement](https://github.com/aspnet/Announcements/issues/353).
To configure a service that depends on `ILogger<T>`, 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<T>` instance provided by DI:
[!code-csharp[](index/samples/3.x/TodoApiSample/Startup2.cs?name=snippet_ConfigureServices&highlight=6-10)]
The preceding highlighted code is a [Func](/dotnet/api/system.func-2) that runs the first time the DI container needs to construct an instance of `MyService`. You can access any of the registered services in this way.
The preceding highlighted code is a [`Func`](/dotnet/api/system.func-2) that runs the first time the DI container needs to construct an instance of `MyService`. You can access any of the registered services in this way.
-->
### No asynchronous logger methods
Logging should be so fast that it isn't worth the performance cost of asynchronous code. If a logging data store is slow, don't write to it directly. Consider writing the log messages to a fast store initially, then moving them to the slow store later. For example, when logging to SQL Server, don't do so directly in a `Log` method, since the `Log` methods are synchronous. Instead, synchronously add log messages to an in-memory queue and have a background worker pull the messages out of the queue to do the asynchronous work of pushing data to SQL Server. For more information, see [this](https://github.com/dotnet/AspNetCore.Docs/issues/11801) GitHub issue.
Logging should be so fast that it isn't worth the performance cost of asynchronous code. If a logging data store is slow, don't write to it directly. Consider writing the log messages to a fast store initially, then moving them to the slow store later. For example, when logging to SQL Server, don't do so directly in a `Log` method, since the `Log` methods are synchronous. Instead, synchronously add log messages to an in-memory queue and have a background worker pull the messages out of the queue to do the asynchronous work of pushing data to SQL Server. For more information, see [Guidance on how to log to a message queue for slow data stores (dotnet/AspNetCore.Docs #11801)](https://github.com/dotnet/AspNetCore.Docs/issues/11801).
<a name="clib"></a>
## Change log levels in a running app
The Logging API doesn't include a scenario to change log levels while an app is running. However, some configuration providers are capable of reloading configuration, which takes immediate effect on logging configuration. For example, the [File Configuration Provider](xref:fundamentals/configuration/index#file-configuration-provider), reloads logging configuration by default. If configuration is changed in code while an app is running, the app can call [IConfigurationRoot.Reload](xref:Microsoft.Extensions.Configuration.IConfigurationRoot.Reload*) to update the app's logging configuration.
The Logging API doesn't include a scenario to change log levels while an app is running. However, some configuration providers are capable of reloading configuration, which takes immediate effect on logging configuration. For example, the [File Configuration Provider](xref:fundamentals/configuration/index#file-configuration-provider), reloads logging configuration by default. If configuration is changed in code while an app is running, the app can call <xref:Microsoft.Extensions.Configuration.IConfigurationRoot.Reload%2A?displayProperty=nameWithType> to update the app's logging configuration.
## ILogger and ILoggerFactory
The <xref:Microsoft.Extensions.Logging.ILogger%601> and <xref:Microsoft.Extensions.Logging.ILoggerFactory> interfaces and implementations are included in the .NET Core SDK. They are also available in the following NuGet packages:
* The interfaces are in [Microsoft.Extensions.Logging.Abstractions](https://www.nuget.org/packages/Microsoft.Extensions.Logging.Abstractions/).
* The default implementations are in [Microsoft.Extensions.Logging](https://www.nuget.org/packages/microsoft.extensions.logging/).
* The interfaces are in [`Microsoft.Extensions.Logging.Abstractions`](https://www.nuget.org/packages/Microsoft.Extensions.Logging.Abstractions/).
* The default implementations are in [`Microsoft.Extensions.Logging`](https://www.nuget.org/packages/microsoft.extensions.logging/).
<!-- review. Why would you want to hard code filtering rules in code? -->
<a name="fric"></a>
@ -860,7 +859,7 @@ The following example shows how to register filter rules in code:
* Log level `Information` and higher.
* All categories starting with `"Microsoft"`.
## Automatically log scope with SpanId, TraceId, ParentId, Baggage, and Tags.
## Automatically log scope with `SpanId`, `TraceId`, `ParentId`, `Baggage`, and `Tags`.
The logging libraries implicitly create a scope object with `SpanId`, `TraceId`, `ParentId`,`Baggage`, and `Tags`. This behavior is configured via <xref:Microsoft.Extensions.Logging.LoggerFactoryOptions.ActivityTrackingOptions>.
@ -891,8 +890,9 @@ To create a custom logger, see [Implement a custom logging provider in .NET](/do
* [View or download sample code](https://github.com/dotnet/AspNetCore.Docs/tree/main/aspnetcore/fundamentals/logging/index/samples/6.x) ([how to download](xref:index#how-to-download-a-sample)).
* <xref:fundamentals/logging/loggermessage>
* Logging bugs should be created in the [github.com/dotnet/runtime/](https://github.com/dotnet/runtime/issues) repo.
* Logging bugs should be created in the [`dotnet/runtime`](https://github.com/dotnet/runtime/issues) GitHub repository.
* <xref:blazor/fundamentals/logging>
:::moniker-end
:::moniker range=">= aspnetcore-3.0 < aspnetcore-6.0"
@ -941,7 +941,7 @@ To create logs, use an <xref:Microsoft.Extensions.Logging.ILogger%601> object fr
The following example:
* Creates a logger, `ILogger<AboutModel>`, which uses a log *category* of the fully qualified name of the type `AboutModel`. The log category is a string that is associated with each log.
* Calls <xref:Microsoft.Extensions.Logging.LoggerExtensions.LogInformation*> to log at the `Information` level. The Log *level* indicates the severity of the logged event.
* Calls <xref:Microsoft.Extensions.Logging.LoggerExtensions.LogInformation%2A> to log at the `Information` level. The Log *level* indicates the severity of the logged event.
[!code-csharp[](index/samples/3.x/TodoApiDTO/Pages/About.cshtml.cs?name=snippet_CallLogMethods&highlight=5,14)]
@ -1024,7 +1024,7 @@ The following commands:
* Set the environment key `Logging:LogLevel:Microsoft` to a value of `Information` on Windows.
* Test the settings when using an app created with the ASP.NET Core web application templates. The `dotnet run` command must be run in the project directory after using `set`.
```cmd
```dotnetcli
set Logging__LogLevel__Microsoft=Information
dotnet run
```
@ -1036,8 +1036,8 @@ The preceding environment setting:
The following [setx](/windows-server/administration/windows-commands/setx) command also sets the environment key and value on Windows. Unlike `set`, `setx` settings are persisted. The `/M` switch sets the variable in the system environment. If `/M` isn't used, a user environment variable is set.
```cmd
setx Logging__LogLevel__Microsoft=Information /M
```console
setx Logging__LogLevel__Microsoft Information /M
```
Consider the following *appsettings.json* file:
@ -1054,8 +1054,8 @@ Consider the following *appsettings.json* file:
The following command sets the preceding configuration in the environment:
```cmd
setx Logging__Console__LogLevel__Microsoft.Hosting.Lifetime=Trace /M
```console
setx Logging__Console__LogLevel__Microsoft.Hosting.Lifetime Trace /M
```
On [Azure App Service](https://azure.microsoft.com/services/app-service/), select **New application setting** on the **Settings > Configuration** page. Azure App Service application settings are: