Logging providers in Microsoft.Extensions.Logging: the defaults added by WebApplication.CreateBuilder (Console, Debug, EventSource, EventLog on Windows), adding OpenTelemetry or Azure Monitor, ClearProviders, how ILoggerFactory fans a call out to one ILogger per provider with per-provider filtering, console formatters and the cost of synchronous providers.
A logging provider (ILoggerProvider) is where logs actually go. WebApplication.CreateBuilder adds Console, Debug, EventSource and, on Windows, EventLog. For production you typically add OpenTelemetry (exporting to Azure Monitor/Application Insights or any OTLP back end), or a third-party logger such as Serilog.
ILoggerFactory holds all providers. When you ask for ILogger<T>, it builds one logger that wraps one provider logger per provider; each call is checked against each provider's filter and written to every provider that accepts it.
The trade-off: every extra provider costs CPU and money on every log call, so production apps usually ClearProviders() and keep one structured sink plus the console.
"Microsoft.Extensions.Logging separates the API I call,
ILogger, from the destinations, which are providers. Out of the boxWebApplication.CreateBuilderregisters four: Console, Debug (the debugger output window), EventSource (an in-process event stream that tools likedotnet-traceanddotnet-monitorcan listen to) and, on Windows, the Windows Event Log. For real production telemetry I add a provider that ships logs somewhere searchable: today that is usually OpenTelemetry, either the Azure Monitor distro for Application Insights or the OTLP exporter to something like Grafana, Datadog or Elastic.Behind the scenes
ILoggerFactorykeeps the list of providers. When DI createsILogger<OrderService>, the factory asks each provider for its own logger for that category and wraps them in a single composite logger. When I callLogInformation, it loops over those provider loggers, checks each one's filter, because each provider can have its own minimum level, and writes to the ones that accept the message. So one call can end up in the console at Debug and in Application Insights only at Warning.The mistake I see is leaving all the defaults on in production and then adding two more sinks on top. In a container the Debug provider is useless and EventLog doesn't exist on Linux; every enabled provider adds work to every log call. I usually call
ClearProviders(), then add the JSON console formatter for the container log stream and OpenTelemetry for the real back end. Pick providers on purpose: each one is a cost on every line you log."
| Provider | Package | Writes to | Good for | Watch out |
|---|---|---|---|---|
| Console | built in | stdout | Containers, local dev | Formatting cost; use the json formatter for log collectors |
| Debug | built in | Debugger output | Local debugging | Useless in production |
| EventSource | built in | Microsoft-Extensions-Logging event source |
dotnet-trace, dotnet-monitor on demand |
Nothing is collected unless a listener attaches |
| EventLog | built in (Windows) | Windows Event Log | Windows services on-prem | Defaults to Warning; not on Linux |
| OpenTelemetry | OpenTelemetry.Extensions.Hosting + exporter |
OTLP or Azure Monitor | Production telemetry | Batching, sampling, cost |
| Azure Monitor distro | Azure.Monitor.OpenTelemetry.AspNetCore |
Application Insights | Azure-hosted apps | Ingestion cost per GB |
| Serilog / NLog | third party | Many sinks/targets | Rich sinks, existing estates | Two configuration systems to learn |
| Situation | Providers |
|---|---|
| Local development | Console (simple formatter) + Debug |
| Container in Azure Container Apps / AKS | Console (json) + OpenTelemetry to Azure Monitor |
| Windows service on-prem | EventLog for Warning+ + a file or OTLP sink |
| Investigating a live process | EventSource via dotnet-trace / dotnet-monitor without redeploying |
A service running in Azure Container Apps had the default providers plus Application Insights and a Serilog file sink inside the container. Removing Debug, EventLog and the file sink and switching the console to the JSON formatter cut CPU spent in logging from about [6%] to [2%] in a dotnet-trace profile, with the same data in Application Insights.
Checks whether the candidate understands the split between the logging API and its destinations, and can choose providers for production.
Green flags
ClearProviders.Red flags
ILogger writes to a file by default.dotnet-trace for logs.ILogger: what you call (Log, IsEnabled, BeginScope).ILoggerProvider: a factory for provider-specific ILoggers, one per category.ILoggerFactory: owns the providers and the filter options, and hands out composite loggers. ILogger<OrderService>.LogInformation(...)
│
▼
Logger (composite, one per category)
┌───────────────┬──────────────┬──────────────────┐
▼ ▼ ▼ ▼
ConsoleLogger DebugLogger EventSourceLogger OpenTelemetryLogger
min: Warning min: Debug min: per listener min: Information
│ │ │ │
stdout debugger out ETW/EventPipe batch ─► exporter
The factory caches one Logger per category. Inside it is an array of MessageLogger entries, each pairing a provider logger with the minimum level and filter that was resolved for that provider and category. A call:
Log<TState>, passing the state object and a formatter delegate. Formatting happens inside each provider, only if it needs the text.AggregateException after trying all of them, so one broken provider does not silently stop others.When configuration reloads, the factory rebuilds the entries, which is how levels change without a restart.
Logging calls run on the request thread. The console provider pushes messages onto a bounded in-memory queue (ConsoleLoggerOptions.MaxQueueLength, default 2.5 million messages in .NET 8+) processed by a background thread; when full, the default QueueFullMode.Wait blocks the caller. OpenTelemetry uses a BatchLogRecordExportProcessor that buffers and exports on a timer. A naive custom provider that writes to a file or a database synchronously puts that I/O on every request.
The EventSource provider writes to an event source named Microsoft-Extensions-Logging. With no listener it is almost free. During an incident you can run:
dotnet-trace collect -p <pid> --providers Microsoft-Extensions-Logging:4:5
to capture logs from a live process (keyword 4 = formatted messages, level 5 = Verbose) without touching configuration.
AddSimpleConsole, AddSystemdConsole and AddJsonConsole choose the output shape. Container log collectors (Azure Monitor Container Insights, Fluent Bit) parse JSON lines far more reliably than multi-line text, and JSON keeps the structured properties.
builder.Logging.ClearProviders().AddJsonConsole() and compare the output with the default.Logging:Console:LogLevel:Default to Error while leaving Debug at Trace, and confirm the two destinations differ.dotnet-trace collect --providers Microsoft-Extensions-Logging:4:5 against the running app and open the .nettrace file in PerfView.ILoggerProvider that counts calls, register it, and check it receives every category.OpenTelemetry logging with the console exporter and compare the record fields with the JSON console output.Choosing providers explicitly for a containerised API.
// Program.cs
using OpenTelemetry.Logs;
var builder = WebApplication.CreateBuilder(args);
// Start clean: Debug and EventLog are useless in a Linux container
builder.Logging.ClearProviders();
// 1. JSON lines to stdout, picked up by the platform's log collector
builder.Logging.AddJsonConsole(o =>
{
o.IncludeScopes = true;
o.TimestampFormat = "O";
});
// 2. OpenTelemetry for the real back end (OTLP endpoint from OTEL_EXPORTER_OTLP_ENDPOINT)
builder.Logging.AddOpenTelemetry(o =>
{
o.IncludeFormattedMessage = true;
o.IncludeScopes = true;
o.AddOtlpExporter();
});
// 3. Keep EventSource so dotnet-trace / dotnet-monitor can attach during incidents
builder.Logging.AddEventSourceLogger();
var app = builder.Build();
app.MapGet("/", (ILogger<Program> logger) =>
{
logger.LogInformation("Health ping at {Utc}", DateTimeOffset.UtcNow);
return TypedResults.Ok();
});
app.Run();
Per-provider levels in configuration:
{
"Logging": {
"LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" },
"Console": { "LogLevel": { "Default": "Warning" } },
"OpenTelemetry": { "LogLevel": { "Default": "Information" } }
}
}
ClearProviders() and add only what you use.AddJsonConsole.LogLevel section applies identically to every provider. Why it is wrong: Provider sections override it, and some providers have their own default (EventLog defaults to Warning). Instead: Check each provider's effective level.dotnet-trace. Instead: Keep it; it costs almost nothing without a listener.The provider list is an operational decision: where will on-call engineers look at 3 a.m., and what does each gigabyte cost? I keep one structured back end (OpenTelemetry to Azure Monitor or OTLP), JSON console for the platform's own log stream, and EventSource for on-demand diagnosis. I avoid writing custom providers; the batching, back-pressure and failure handling are harder than they look.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Console (json) only | Platform already collects stdout (Container Apps, AKS) | Collector cost, limited querying | When you need traces correlated with logs |
| OpenTelemetry exporter | Vendor-neutral, correlated with traces and metrics | Exporter config, batching | Tiny tools where console is enough |
| Serilog/NLog as the provider | Existing estate, rich sinks | Second config model | Greenfield apps already on OpenTelemetry |
| Custom provider | A sink nobody supports | You own batching and failures | Almost always |
Decorator wraps an object in another object that implements the same interface, adds behaviour before or after delegating, and is invisible to callers. Decorators stack: logging around caching around the real repository. Each concern is one small class, so the original stays untouched (Open/Closed).
.NET uses it everywhere: GZipStream(BufferedStream(FileStream)), CryptoStream, and DelegatingHandler pipelines in HttpClient.
The built-in container has no Decorate method. You register the inner type concretely and the interface with a factory delegate, use a keyed inner service, or use Scrutor's Decorate<TService, TDecorator>().
The trade-off is that order matters and long chains are harder to debug.
First I measure: Application Insights tells me which endpoint is slow and at what percentile, and whether time goes into dependencies like SQL or HTTP. Then I reproduce it on a Release build and run the Visual Studio Performance Profiler (Alt+F2): CPU Usage for hot paths, Database for query count and duration, .NET Object Allocation Tracking for GC pressure, and .NET Async for slow awaits. In an environment where I can't use Visual Studio, dotnet-counters shows live metrics like thread pool queue length and GC, and dotnet-trace captures CPU samples. I fix the biggest cause, often an N+1 query, re-measure against the baseline, and add a load test so it doesn't regress.
Your code always logs through ILogger<T>; the choice is what sits underneath.
AddSerilog). Destinations are sinks (Seq, files, Elastic, OTLP); enrichers add properties such as machine name or user id. It has rich destructuring and a bootstrap logger for start-up failures.UseNLog) uses targets and layouts, configured in nlog.config, popular in older enterprise estates.AddOpenTelemetry().WithLogging() exports to OTLP or Azure Monitor, with logs correlated to traces and metrics.For a new .NET 10 service on Azure I'd start with built-in + OpenTelemetry; I'd keep Serilog or NLog where a team already relies on their sinks. The trade-off is fewer moving parts versus richer formatting and sink choice.
Last updated 23 Nov 2026.