📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What logging providers come with .NET (console, debug, EventSource, EventLog) and which ones do you add for Application Insights and OpenTelemetry? How does ILoggerFactory send one log call to several providers, and how do you choose and configure them?

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.

Junior Theory Beginner application-insights aspnet-core iloggerfactory logging logging-providers opentelemetry

🎯 Key points

  • WebApplication.CreateBuilder adds Console, Debug and EventSource everywhere, plus EventLog when running on Windows
  • An ILoggerProvider creates a provider-specific ILogger per category; ILoggerFactory combines them into one composite logger per category
  • Each log call is checked against each provider's own filter (level per provider and category) and written to every provider that accepts it
  • builder.Logging.ClearProviders() then add only what you need in production
  • OpenTelemetry (builder.Logging.AddOpenTelemetry / UseAzureMonitor / OTLP exporter) is the current way to ship to Application Insights and other back ends
  • Console provider queues messages to a background thread; its formatters are simple, systemd and json
  • EventSource provider (Microsoft-Extensions-Logging) lets dotnet-trace collect logs from a running process without config changes

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"Microsoft.Extensions.Logging separates the API I call, ILogger, from the destinations, which are providers. Out of the box WebApplication.CreateBuilder registers four: Console, Debug (the debugger output window), EventSource (an in-process event stream that tools like dotnet-trace and dotnet-monitor can 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 ILoggerFactory keeps the list of providers. When DI creates ILogger<OrderService>, the factory asks each provider for its own logger for that category and wraps them in a single composite logger. When I call LogInformation, 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."


The built-in and common providers

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

Choosing

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

Production example

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.

🔍 What the interviewer is checking

Checks whether the candidate understands the split between the logging API and its destinations, and can choose providers for production.

Green flags

  • Names the default providers and knows EventLog is Windows-only.
  • Explains the factory's per-provider loggers and per-provider filters.
  • Mentions OpenTelemetry or Azure Monitor for production and ClearProviders.
  • Knows logging runs on the request thread and that batching matters.

Red flags

  • Thinks ILogger writes to a file by default.
  • Adds several sinks to one back end without noticing the duplication.
  • Has never heard of the EventSource provider or dotnet-trace for logs.

📚 Learn in depth

1. The three interfaces

  • 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

2. How the fan-out works

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:

  1. Loops over the entries.
  2. Skips entries whose level is above the call's level.
  3. Calls the provider logger's Log<TState>, passing the state object and a formatter delegate. Formatting happens inside each provider, only if it needs the text.
  4. Collects exceptions thrown by providers and rethrows an 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.

3. Synchronous vs batching providers

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.

4. EventSource: logs on demand

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.

5. Console formatters

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.

Try it yourself

  1. In a new web app, call builder.Logging.ClearProviders().AddJsonConsole() and compare the output with the default.
  2. Set Logging:Console:LogLevel:Default to Error while leaving Debug at Trace, and confirm the two destinations differ.
  3. Run dotnet-trace collect --providers Microsoft-Extensions-Logging:4:5 against the running app and open the .nettrace file in PerfView.
  4. Write a tiny ILoggerProvider that counts calls, register it, and check it receives every category.
  5. Add OpenTelemetry logging with the console exporter and compare the record fields with the JSON console output.

💻 Code

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" } }
  }
}

⚠ Common mistakes

  • Mistake: Leaving every default provider on in production containers. Why it is wrong: Debug and EventLog add work for no benefit on Linux. Instead: ClearProviders() and add only what you use.
  • Mistake: Shipping logs to the same back end twice (Serilog sink plus OpenTelemetry exporter). Why it is wrong: Doubles ingestion cost and creates duplicate entries. Instead: Choose one path to each back end.
  • Mistake: Writing a custom provider that does synchronous file or HTTP I/O. Why it is wrong: It blocks the request thread on every log call. Instead: Buffer and write in the background, or use an existing batching provider.
  • Mistake: Using the simple console formatter in Kubernetes. Why it is wrong: Multi-line text and stack traces break log collectors and lose structured properties. Instead: Use AddJsonConsole.
  • Mistake: Assuming the general 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.
  • Mistake: Removing EventSource along with the rest. Why it is wrong: You lose the ability to collect logs from a live process with dotnet-trace. Instead: Keep it; it costs almost nothing without a listener.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate describes the composite logger wrapping one logger per provider. Why: Checks they can relate the provider fan-out and wrapping to structural design patterns.
    How to answer

    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.

  2. When: Candidate mentions the EventSource provider or dotnet-trace. Why: Checks they can use dotnet-trace and Application Insights to investigate a live service.
    How to answer

    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.

  3. When: Candidate mentions Serilog or NLog as alternative providers. Why: Checks they can compare Serilog, NLog and built-in logging with OpenTelemetry as provider choices.
    How to answer

    Your code always logs through ILogger<T>; the choice is what sits underneath.

    • Serilog replaces the provider pipeline (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.
    • NLog (UseNLog) uses targets and layouts, configured in nlog.config, popular in older enterprise estates.
    • Built-in + OpenTelemetry: 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.

↩ Usually asked after

More in Logging

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me