skip to content

In ASP.NET Core 10, which logging providers does WebApplication.CreateBuilder register, and what do ClearProviders and AddJsonConsole change about where log entries go?

level: middleimportance: should knowfreq 42%

answer

  1. four providers, one of them Windows-only
  2. EventLog starts at Warning
  3. ClearProviders = RemoveAll<ILoggerProvider>
  4. FormatterName "json"
  5. Logging:Console:LogLevel beats Logging:LogLevel

basics

~10 s

WebApplication.CreateBuilder registers Console, Debug and EventSource, plus EventLog on Windows. ClearProviders removes every provider registered so far; AddJsonConsole adds the console provider with its formatter set to json, one JSON object per entry.

solid answer

~40 s

The host's default services add the `Console` provider (except in the browser or WASI), `Debug`, `EventSource` and, on Windows, `EventLog`, which gets a code filter to `Warning` and above before configuration is applied, so configuration can override it. `builder.Logging.ClearProviders()` is just `Services.RemoveAll<ILoggerProvider>()`: it removes what was registered before the call, so call it first and add providers afterwards. `AddJsonConsole()` calls `AddConsole` with `FormatterName = "json"`; the console provider is registered with `TryAddEnumerable`, so you still get one console provider, now writing one JSON object per line (`EventId`, `LogLevel`, `Category`, `Message`, `State`, and `Exception`, `Scopes` or `Timestamp` when present or enabled). Without `ClearProviders`, Debug and EventSource keep running beside it. Levels can differ per provider: a `Logging:Console:LogLevel` rule wins over any `Logging:LogLevel` rule for the console provider.

code

csharp · 6 lines
csharp
var builder = WebApplication.CreateBuilder(args);

builder.Logging.ClearProviders();               // removes Console, Debug, EventSource, EventLog
builder.Logging.AddJsonConsole(o => o.IncludeScopes = true);

var app = builder.Build();

go deeper

for a junior

Recall the default providers, that ClearProviders removes them, and that AddJsonConsole makes the console print one JSON object per entry.

for a middle

Explain what ClearProviders really removes, how FormatterName selects the JSON formatter, which fields it writes by default, and how a provider-specific LogLevel block outranks the general one.

for a senior

Choose the provider set for container hosting, avoid duplicate outputs, and watch the console queue: MaxQueueLength and QueueFullMode decide whether a burst blocks requests or drops lines.

for a principal

Set the organisation's output contract, one JSON stream with agreed fields, and decide which provider changes need review because they alter what every collector receives.

## Providers and the factory An `ILogger` does not write anything itself. The `LoggerFactory` holds a list of **providers** (`ILoggerProvider` implementations); each logger fans every enabled entry out to one inner logger per provider, and each provider sends it somewhere: standard output, the debugger, an event pipe, the Windows Event Log, or an exporter you add. ## What WebApplication.CreateBuilder registers The default host setup in `Microsoft.Extensions.Hosting` adds, in this order: | Provider | Configuration alias | Notes | |---|---|---| | `ConsoleLoggerProvider` | `Console` | skipped when running in the browser or on WASI | | `DebugLoggerProvider` | `Debug` | writes to an attached debugger; ignores scopes | | `EventSourceLoggerProvider` | `EventSource` | feeds the `Microsoft-Extensions-Logging` event source used by tools such as `dotnet-trace` | | `EventLogLoggerProvider` | `EventLog` | Windows only; a code filter keeps it at `Warning` and above unless configuration says otherwise | The same setup binds the `Logging` configuration section and sets `ActivityTrackingOptions` to `SpanId | TraceId | ParentId`. ## ClearProviders `ClearProviders()` is a one-liner over the service collection: `Services.RemoveAll<ILoggerProvider>()`. Two consequences follow: - It removes **only what is registered at that moment**. Providers added after the call stay, so the usual shape is `ClearProviders()` first, then the providers you want. - It does not touch filters, scopes or the `Logging` section binding; only the destinations change. Teams call it when the defaults are wrong for their hosting: a container platform that collects standard output wants exactly one JSON stream, not a console stream plus Debug output. ## AddJsonConsole ```csharp builder.Logging.ClearProviders(); builder.Logging.AddJsonConsole(options => { options.IncludeScopes = true; options.UseUtcTimestamp = true; options.TimestampFormat = "O"; }); ``` `AddJsonConsole` calls `AddConsole` and sets `ConsoleLoggerOptions.FormatterName` to `"json"` (`ConsoleFormatterNames.Json`). Since `AddConsole` registers the provider with `TryAddEnumerable`, calling both `AddConsole` and `AddJsonConsole` still leaves a single console provider. Each entry becomes one JSON object on one line: - always `EventId`, `LogLevel`, `Category` and `Message`; - `Exception` when one was passed; - `State` with the message's key/value pairs, numbers kept as JSON numbers; - `Scopes` only when `IncludeScopes` is `true` (default `false`); - `Timestamp` only when `TimestampFormat` is set (default `null`). `JsonConsoleFormatterOptions.JsonWriterOptions` passes options to the underlying `Utf8JsonWriter`; leaving `Indented` off matters, because collectors that read standard output line by line split an indented object into fragments. The same choice can be made in configuration with `Logging:Console:FormatterName` set to `json` and the options under `Logging:Console:FormatterOptions`. ## Per-provider levels Configuration can set levels for one provider by nesting a `LogLevel` block under the provider's alias: ```json { "Logging": { "LogLevel": { "Default": "Information", "Warehouse": "Debug" }, "Console": { "LogLevel": { "Default": "Information" } } } } ``` The rule selector prefers **any** rule naming the provider over every rule that does not, before comparing category lengths. So, for the console provider, `Console:LogLevel:Default` beats the more specific `Warehouse` entry in the general block: Warehouse `Debug` lines reach the debugger but not standard output. To lower one category for the console only, put the category under `Console:LogLevel` too. ## The console writes on a background thread `ConsoleLogger` formats the entry on the calling thread and enqueues it; a background thread writes to the console. `ConsoleLoggerOptions.MaxQueueLength` defaults to 2,500 and `QueueFullMode` to `Wait`, so a burst that fills the queue blocks the threads that are logging until the writer catches up. `DropWrite` drops new entries instead. On a busy picking service, too much console output turns into request latency long before it turns into lost lines.

  • A colleague calls AddJsonConsole without ClearProviders. What is different from calling ClearProviders first?
    The console provider switches to the JSON formatter either way, because `AddConsole` uses `TryAddEnumerable` and only the formatter name changes. Without `ClearProviders`, the Debug and EventSource providers (and EventLog on Windows) still receive every enabled entry, so filters and cost apply to all of them and Windows Event Log may still get warnings.
  • Under a log burst, request latency on a picking API rises while CPU stays moderate. How can the console provider cause that?
    The console logger queues formatted entries for a single background writer. When the queue reaches `MaxQueueLength` (2,500 by default) and `QueueFullMode` is `Wait`, the threads that log block until space frees up. Lower the volume through levels, or accept loss with `DropWrite`.

  • ClearProviders also removes providers that are added after it.
  • Calling AddJsonConsole adds a second console provider next to the plain one.
  • The longest category always wins, even against a Logging:Console:LogLevel rule.
  • The EventLog provider is registered on Linux containers too.
  • The JSON console formatter writes a Timestamp field by default.