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

📚 Interview question

Serilog, NLog, or the built-in Microsoft.Extensions.Logging with OpenTelemetry: how does each plug into ASP.NET Core, what are sinks, targets and enrichers, and how would you choose for a new .NET 10 service today?

Comparing logging stacks for ASP.NET Core on .NET 10: Serilog (AddSerilog, two-stage bootstrap, sinks, enrichers, Serilog.Settings.Configuration), NLog (UseNLog, targets, layouts, nlog.config), and the built-in abstraction with OpenTelemetry exporters; how each sits behind ILogger, what OpenTelemetry changes, and a decision guide.

Intermediate Theory Intermediate aspnet-core logging nlog observability opentelemetry serilog

🎯 Key points

  • Application code always logs through ILogger<T>; Serilog and NLog plug in underneath as the provider
  • Serilog: builder.Services.AddSerilog(...) (Serilog.AspNetCore 10.x for .NET 10), sinks for destinations, enrichers add properties, configured in code or via Serilog.Settings.Configuration
  • Serilog two-stage init: a bootstrap logger catches start-up failures before the host is built
  • NLog: builder.Logging.ClearProviders(); builder.Host.UseNLog(), targets and layouts in nlog.config or appsettings; NLog.Web.AspNetCore 6.x supports .NET 10
  • Built-in + OpenTelemetry: AddOpenTelemetry().WithLogging() with OTLP or Azure Monitor exporters; logs correlated with traces and metrics
  • OpenTelemetry has become the vendor-neutral transport; Serilog and NLog can also export OTLP
  • Choose by back end and estate: greenfield on Azure → built-in + OTel; existing Serilog/NLog estate → keep it and add OTLP
  • Avoid two pipelines shipping the same logs to the same back end

⏱ 30-second 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.

🗣 Full answer (senior)

How I would answer this in an interview

"The first thing to say is that application code shouldn't care: classes take ILogger<T>, and whatever library sits underneath is a hosting decision in Program.cs. Serilog and NLog both plug in as providers behind that abstraction.

Serilog is built around structured events from the start. You call builder.Services.AddSerilog(...), configure a pipeline of enrichers, which add properties to every event like environment or the current user, and sinks, which are destinations like Seq, Elastic, files or OTLP. It supports {@Object} destructuring, and the recommended set-up uses a bootstrap logger so failures before the host is built are still logged. NLog has a similar model with different words: targets for destinations, layouts for formatting, rules for routing, usually in nlog.config. It's very common in older enterprise code and is fast and mature. Both have current versions for .NET 10: Serilog.AspNetCore 10.x and NLog.Web.AspNetCore 6.x.

The third option is no third-party logger at all: the built-in providers plus OpenTelemetry. AddOpenTelemetry().WithLogging() exports log records through OTLP or the Azure Monitor distro, and because the same SDK handles traces and metrics, every log carries the trace id and lands next to the request it belongs to. The mistake I see is running Serilog with an Application Insights sink and the Azure Monitor distro, which ships every log twice and doubles the bill. For a greenfield service on Azure I default to built-in plus OpenTelemetry; if a team already has a mature Serilog set-up with Seq, I keep it and add an OTLP sink rather than rip it out. Choose the transport first, OpenTelemetry, then the library is a detail."


Side by side

Built-in + OpenTelemetry Serilog NLog
Plugs in via builder.Logging + AddOpenTelemetry() builder.Services.AddSerilog() builder.Host.UseNLog()
Destinations Providers + exporters (OTLP, Azure Monitor) Sinks Targets
Extra properties Scopes, ActivityTrackingOptions, processors Enrichers, LogContext Layout renderers, ScopeContext
Configuration Logging section + code Code or Serilog section nlog.config or NLog section
Trace correlation Native Via enricher / OTLP sink Via layout renderer / OTLP target
Start-up failures Lost before host builds Bootstrap logger Set up before host

How to choose

Situation Choice
New service, Azure, Application Insights Built-in + Azure Monitor OpenTelemetry distro
New service, vendor-neutral back end (Grafana, Datadog, Elastic) Built-in + OTLP exporter
Team uses Seq heavily, wants destructuring Serilog with Seq sink (+ OTLP for traces)
Large existing NLog estate Keep NLog; add OTLP target; don't rewrite
Need several local sinks (rolling files on-prem) Serilog or NLog

Production example

A team running Serilog with both an Application Insights sink and the classic Application Insights SDK found every trace line ingested twice, about [45] GB a month instead of [22]. Removing the sink and keeping the SDK (later the OpenTelemetry distro) halved ingestion without losing any data.

🔍 What the interviewer is checking

Checks whether the candidate can compare logging stacks on their merits and make a pragmatic choice rather than a fashionable one.

Green flags

  • Says application code depends only on ILogger<T>.
  • Explains sinks/targets and enrichers correctly.
  • Knows the Serilog bootstrap logger and flushing on shutdown.
  • Positions OpenTelemetry as the transport and avoids duplicate pipelines.

Red flags

  • Injects Serilog.ILogger everywhere.
  • Thinks OpenTelemetry is "another logging library like Serilog".
  • Recommends rewriting an existing estate without a reason.

📚 Learn in depth

1. Where each library sits

  your code ──► ILogger<T> (Microsoft.Extensions.Logging)
                     │
     ┌────────────────┼───────────────────────────┐
     ▼                ▼                          ▼
 built-in providers  SerilogLoggerProvider      NLogLoggerProvider
 (Console, OTel)        │                          │
     │               enrichers → filters        rules → layouts
     │                  │                          │
  exporters          sinks                      targets
 (OTLP, Azure       (Seq, File, OTLP,          (File, Database,
  Monitor)           Elastic...)                OTLP...)

With AddSerilog, Serilog registers its own ILoggerFactory replacement by default, so built-in providers are bypassed unless you pass writeToProviders: true. NLog adds a provider; you normally ClearProviders() first.

2. Serilog essentials

  • Two-stage initialisation: Log.Logger = new LoggerConfiguration().WriteTo.Console().CreateBootstrapLogger(); before building the host, then AddSerilog((services, lc) => lc.ReadFrom.Configuration(...)) replaces it once configuration and DI exist.
  • Enrichers: Enrich.FromLogContext(), Enrich.WithMachineName(), custom ILogEventEnricher.
  • Request logging: app.UseSerilogRequestLogging() writes one summary event per request instead of the framework's several lines.
  • Sinks are mostly asynchronous or batched (Serilog.Sinks.Async, periodic batching for HTTP sinks).

3. NLog essentials

  • nlog.config declares <targets> (file, console, database, OTLP), <rules> routing loggers by name and level to targets, and layouts such as ${longdate}|${level}|${logger}|${message}.
  • AsyncWrapper targets buffer writes. NLog 6 (2025) removed some legacy features and improved AOT and trimming support.

4. OpenTelemetry's role

OpenTelemetry defines the data model and the OTLP protocol for logs, traces and metrics. In .NET, the logging bridge is an ILoggerProvider that turns each log call into a LogRecord with attributes, scopes and the current TraceId/SpanId, then batches it to an exporter. The Azure Monitor distro (Azure.Monitor.OpenTelemetry.AspNetCore, 1.x) wraps this for Application Insights. Because OTLP is vendor-neutral, changing back end is a configuration change.

5. Configuration and reload

All three support reading levels from configuration. Built-in filters reload with IConfiguration; Serilog needs ReadFrom.Configuration with a reloadable minimum level (LoggingLevelSwitch) for live changes; NLog watches nlog.config with autoReload="true".

6. Cost of mixing

Every pipeline that ships to the same back end doubles cost and creates confusing duplicates. Keep one path per destination, and decide whether the framework's request logs, Serilog request logging or OpenTelemetry request telemetry is the one you keep.

Try it yourself

  1. Build the same small API three times, once with each stack, logging the same events to the console in JSON, and compare the output.
  2. With Serilog, throw an exception in Program.cs before Build() and check the bootstrap logger records it.
  3. Add UseSerilogRequestLogging() and compare log line counts per request with the default framework logging.
  4. Run the .NET Aspire dashboard or a local OpenTelemetry Collector and send OTLP logs from all three stacks.
  5. Turn on both a Serilog Application Insights sink and the Azure Monitor distro in a test resource and count duplicate traces with KQL.

💻 Code

The two set-ups I see most: built-in with OpenTelemetry, and Serilog with a bootstrap logger.

// Option A: built-in logging + OpenTelemetry (greenfield on Azure)
// Package: Azure.Monitor.OpenTelemetry.AspNetCore
using Azure.Monitor.OpenTelemetry.AspNetCore;

var builder = WebApplication.CreateBuilder(args);

builder.Logging.ClearProviders();
builder.Logging.AddJsonConsole();

// Logs, traces and metrics to Application Insights; connection string from
// APPLICATIONINSIGHTS_CONNECTION_STRING (an environment variable, never in source control)
builder.Services.AddOpenTelemetry().UseAzureMonitor();

var app = builder.Build();
app.MapGet("/ping", (ILogger<Program> log) => { log.LogInformation("Ping"); return TypedResults.Ok(); });
app.Run();
// Option B: Serilog with two-stage initialisation
// Packages: Serilog.AspNetCore (10.x), Serilog.Sinks.Seq, Serilog.Sinks.OpenTelemetry
using Serilog;

Log.Logger = new LoggerConfiguration()
    .WriteTo.Console()
    .CreateBootstrapLogger(); // catches failures before the host exists

try
{
    var builder = WebApplication.CreateBuilder(args);

    builder.Services.AddSerilog((services, lc) => lc
        .ReadFrom.Configuration(builder.Configuration)
        .ReadFrom.Services(services)
        .Enrich.FromLogContext()
        .WriteTo.Console(new Serilog.Formatting.Compact.RenderedCompactJsonFormatter())
        .WriteTo.OpenTelemetry()); // OTLP endpoint from OTEL_EXPORTER_OTLP_ENDPOINT

    var app = builder.Build();
    app.UseSerilogRequestLogging(); // one summary event per request
    app.MapGet("/ping", (ILogger<Program> log) => { log.LogInformation("Ping"); return TypedResults.Ok(); });
    app.Run();
}
catch (Exception ex)
{
    Log.Fatal(ex, "Host terminated unexpectedly");
}
finally
{
    Log.CloseAndFlush(); // flush buffered sinks before exit
}

⚠ Common mistakes

  • Mistake: Referencing Serilog.ILogger or NLog's Logger directly in application classes. Why it is wrong: It couples every class to one library and makes switching or testing harder. Instead: Depend on ILogger<T> and configure the library in Program.cs.
  • Mistake: Shipping the same logs through two pipelines (Serilog sink plus OpenTelemetry exporter). Why it is wrong: Duplicate entries and double ingestion cost. Instead: One path per back end.
  • Mistake: Skipping the Serilog bootstrap logger. Why it is wrong: Configuration or DI errors before Build() vanish, and the app exits silently. Instead: Use CreateBootstrapLogger and CloseAndFlush in finally.
  • Mistake: Forgetting to flush on shutdown. Why it is wrong: Batched sinks lose the last events, often the ones explaining a crash. Instead: Log.CloseAndFlush() for Serilog; NLog LogManager.Shutdown(); OpenTelemetry flushes when the host disposes.
  • Mistake: Rewriting a working NLog or Serilog estate because "OpenTelemetry is the standard". Why it is wrong: Risk and effort for little benefit. Instead: Add an OTLP sink or target and migrate gradually.
  • Mistake: Using a synchronous file or database sink in a web app. Why it is wrong: I/O on the request thread adds latency. Instead: Async or batched sinks, or ship to a collector.
  • Mistake: Keeping both framework request logs and UseSerilogRequestLogging. Why it is wrong: Several lines per request where one would do. Instead: Set Microsoft.AspNetCore to Warning when using Serilog request logging.

🏛 Senior insight: trade-offs

The real decision is the transport and back end, not the logging library. OpenTelemetry has become the common language between .NET and observability vendors, so I make sure whatever library we use can speak OTLP and carries trace context. Beyond that I favour fewer moving parts: the built-in abstraction plus OpenTelemetry covers most services, and I only add Serilog or NLog when a feature (Seq, destructuring, local rolling files) earns its place.

Option When it fits Cost When not to
Built-in + OpenTelemetry Greenfield, cloud-hosted, traces needed Fewer formatting features Heavy local-file or on-prem sink needs
Serilog Seq users, rich sinks and enrichers Extra config model, bootstrap set-up Teams that want minimal dependencies
NLog Existing NLog estates, on-prem targets XML config, another model Greenfield cloud services
Two libraries at once Never intentionally Duplicates, confusion Always

🔗 Follow-ups the interviewer may ask

  1. When: Candidate says Serilog or NLog replaces the provider pipeline. Why: Checks they understand how providers sit behind ILoggerFactory, which is where these libraries plug in.
    How to 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.

  2. When: Candidate mentions Serilog destructuring or structured events. Why: Checks they understand message templates, which all three stacks rely on.
    How to answer

    Structured logging records an event: a constant message template plus named properties, instead of a pre-built string. In logger.LogInformation("Order {OrderId} placed in {ElapsedMs} ms", id, ms), the provider gets the template and the values separately, so OrderId and ElapsedMs become queryable fields (Application Insights customDimensions, OpenTelemetry attributes, Seq properties).

    With string interpolation ($"Order {id} placed") the provider only sees a finished string: no properties, a different message every time, and the string is built even when the level is disabled. Analyser CA2254 warns about this.

    The trade-off: templates take discipline in naming, but they turn logs from text you grep into data you can filter, group and alert on.

↩ Usually asked after

More in Logging

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me