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

📚 Interview question

What is your log level strategy for a .NET 10 service in production? What belongs at Trace, Debug, Information, Warning, Error and Critical, how do you change levels at runtime without a redeploy, and how do you stop a log flood from hurting the service and the bill?

Production log level policy for .NET: what each level means, category filters, changing levels at runtime (reloadable configuration, Azure App Configuration, Serilog level switches), log sampling and buffering, rate limiting, and protecting the service and budget from log floods.

Mid-Level Theory Intermediate aspnet-core azure-app-configuration log-levels log-management observability sampling

🎯 Key points

  • Levels are a contract: Information = business events worth keeping, Warning = handled but unexpected, Error = a failed operation needing attention, Critical = the service cannot work
  • Production default: Information for your namespaces, Warning for Microsoft.* and System.Net.Http.* categories
  • Filters are per category in the Logging section; the most specific category prefix wins
  • Runtime changes: reloadOnChange config, Azure App Configuration refresh with a sentinel key, or a Serilog LoggingLevelSwitch, with an automatic revert
  • Log sampling and per-request buffering (Microsoft.Extensions.Telemetry) keep detail for failed requests without logging every success
  • A log flood is a performance problem: synchronous sinks, string formatting and exporter queues cost CPU, memory and latency
  • Exceptions logged once at the boundary, not at every layer
  • Guard rails: ingestion alerts and daily caps per workspace, [LoggerMessage] for hot paths

⏱ 30-second answer

I treat log levels as a contract the whole team follows:

  • Information: business events and request outcomes worth keeping. Warning: handled but unexpected (a retry, a fallback). Error: an operation failed and someone may need to act. Critical: the service cannot function.
  • Debug/Trace are off in production by default (volume, CPU and payloads with personal data), but can be switched on temporarily for one category at runtime when troubleshooting.
  • Defaults: Information for our namespaces, Warning for Microsoft.*, set per category in configuration.

To debug live, I change levels through reloadable configuration or Azure App Configuration, time-boxed and reverted. To prevent floods I use sampling or per-request buffering, log exceptions once, and alert on ingestion volume. The trade-off is detail when you need it versus cost, overhead and privacy risk all the time.

🗣 Full answer (senior)

How I would answer this in an interview

"I start by agreeing what each level means, because a level is only useful if everyone uses it the same way. Information is for events we want to keep: an order was placed, a job finished, a request completed. Warning is something handled but unexpected, like a retry that succeeded or a fallback to cached data. Error means an operation failed and may need a human; Critical means the service itself can't work, like losing its database. Debug and Trace are for developers and are off in production. Then I set filters per category: our own namespaces at Information, Microsoft.AspNetCore and System.Net.Http.HttpClient at Warning, because the framework is chatty and the request telemetry already covers what it would log.

For live debugging I don't redeploy. In .NET the logging filters are bound through IOptionsMonitor, so if configuration reloads, the new levels apply immediately. In Azure I keep log levels in Azure App Configuration with a sentinel key, so I can turn one category to Debug for 30 minutes and then set it back; with Serilog I'd use a LoggingLevelSwitch. For example, at [company] we [chased an intermittent payment failure by enabling Debug on one namespace for an hour, which found the cause without a release]. To keep detail without paying for it on every request, I use per-request buffering: buffer Debug logs in memory and flush them only if the request fails.

The mistake I see is logging the same exception at every layer and logging inside tight loops, so one bad dependency turns into a million lines a minute, the exporter queue fills and latency climbs. Logs are a budget: spend them on decisions and failures, not on proof that the code ran."


What goes at each level

Level Meaning Example Production default
Trace Step-by-step internals, may include payloads Serialised request body Off
Debug Developer diagnostics Cache key computed, branch taken Off (on briefly when debugging)
Information Business events and outcomes Order {OrderId} placed for {Amount} On for own code
Warning Handled, unexpected, may need watching Retry 2 of 3 succeeded; fallback used On
Error An operation failed Payment capture failed after retries On, drives alerts
Critical Service unusable Cannot reach database at startup On, pages someone

Ways to change levels at runtime

Mechanism How it works Notes
appsettings.json with reloadOnChange File watcher reloads config; LoggerFilterOptions updates Works with Kubernetes ConfigMaps mounted as a directory (not subPath)
Azure App Configuration Provider polls; a sentinel key triggers refresh Central, audited, label per environment
App Service app settings Changing them restarts the app Not truly live
Serilog LoggingLevelSwitch Switch changed via config or an admin endpoint Protect the endpoint

Flood controls

Control What it stops
Category filters Framework noise
Log once at the boundary Duplicate stack traces
Random probabilistic sampling of Information Volume from healthy traffic
Per-request buffering Debug detail on every success
[LoggerMessage] source generator Formatting and boxing cost on hot paths
Ingestion alert and daily cap Runaway bill

Production example

A dependency outage made a worker log a full exception for each of [8,000] messages per minute, at three layers each. The OpenTelemetry exporter queue filled, p99 latency of the co-hosted API rose from [120 ms] to [900 ms], and the workspace ingested [30 GB] in two hours. Logging once at the handler boundary, adding a circuit breaker and sampling repeated errors cut volume by over [95%] in the next outage.

🔍 What the interviewer is checking

Checks whether the candidate runs logging deliberately in production: clear level semantics, safe runtime changes and protection against floods.

Green flags

  • Gives concrete meanings and examples for each level.
  • Knows category filters and that the most specific rule wins.
  • Changes levels at runtime without a restart and reverts them.
  • Treats a log flood as both a performance and a cost problem.
  • Logs exceptions once.

Red flags

  • "Everything at Information and filter later."
  • Redeploys to change a log level.
  • Uses Error for validation failures.

📚 Learn in depth

1. How .NET decides whether to log

logger.LogDebug(...)
   |
   v
Logger (per category) --> for each provider: is level enabled for (provider, category)?
   |                              |
   |                     LoggerFilterOptions rules
   |                     (most specific provider + category prefix wins)
   v
If enabled: format message, attach scopes, write to provider

IsEnabled is cheap; formatting is not. The [LoggerMessage] source generator checks IsEnabled first and avoids boxing value-type arguments, which matters at thousands of calls per second.

Rules come from the Logging section:

"Logging": {
  "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" },
  "OpenTelemetry": { "LogLevel": { "Default": "Information" } }
}

A provider-specific section (here OpenTelemetry) overrides the general LogLevel for that provider.

2. Why runtime changes work

LoggerFactory subscribes to IOptionsMonitor<LoggerFilterOptions>. When configuration reloads, the options monitor fires, the factory recomputes filters, and existing ILogger instances pick up the new rules. Nothing restarts. Azure App Configuration plugs into the same pipeline: AddAzureAppConfiguration with ConfigureRefresh(r => r.Register("Logging:Sentinel", refreshAll: true)) plus app.UseAzureAppConfiguration() (or a background refresher) reloads when the sentinel key changes.

3. Sampling and buffering

The Microsoft.Extensions.Telemetry package (from the .NET 9 era onwards) adds:

  • Random probabilistic sampling: keep, say, 10% of Information logs, all Warnings and above.
  • Buffering: hold lower-level logs in memory (globally or per incoming request) and flush them only when something goes wrong, so a failed request comes with its Debug context.

If you use the Azure Monitor distro, trace sampling also affects logs that belong to sampled-out traces in recent versions, so check how your distro version handles log sampling before stacking another sampler on top.

4. Why a flood hurts the service

hot loop -> LogError(ex) x 10,000/s
   -> string formatting + stack trace capture (CPU, allocations, GC)
   -> exporter batch queue fills -> drops or back-pressure
   -> console sink in a container: synchronous writes to stdout block threads

Console logging in containers is a classic trap: the console provider queues messages, but at sustained high volume it can still block and add latency. Use the OTLP exporter or JSON console with sensible levels.

5. A policy you can write down

  1. Every Error must be actionable or carry enough context to start an investigation.
  2. Exceptions are logged once, where they are handled.
  3. No logs inside per-item loops above Debug unless rate-limited.
  4. Debug is enabled per category, for a time box, with an owner.

Try it yourself

  1. Change Logging:LogLevel in appsettings.json while the app runs and confirm new Debug lines appear without a restart.
  2. Benchmark logger.LogInformation("x {A}", 42) vs a [LoggerMessage] method with BenchmarkDotNet when the level is disabled.
  3. Add AddRandomProbabilisticSampler(0.1, LogLevel.Information) and count lines in Seq before and after.
  4. Wire Azure App Configuration with a sentinel key and time how long a level change takes to apply.

💻 Code

Per-category levels, runtime refresh from Azure App Configuration, and sampling of healthy-traffic logs:

// Program.cs (.NET 10)
using Azure.Identity;

var builder = WebApplication.CreateBuilder(args);

// Central, runtime-changeable levels. Changing "Logging:Sentinel" triggers a full refresh.
builder.Configuration.AddAzureAppConfiguration(o =>
    o.Connect(new Uri(builder.Configuration["AppConfig:Endpoint"]!), new DefaultAzureCredential())
     .Select("Logging:*", labelFilter: builder.Environment.EnvironmentName)
     .ConfigureRefresh(r => r.Register("Logging:Sentinel", refreshAll: true)
                             .SetRefreshInterval(TimeSpan.FromSeconds(30))));
builder.Services.AddAzureAppConfiguration();

// Keep 10% of Information and below; Warning and above are always kept.
builder.Logging.AddRandomProbabilisticSampler(0.1, LogLevel.Information);

var app = builder.Build();
app.UseAzureAppConfiguration(); // checks for refresh on incoming requests
app.MapGet("/", () => "ok");
app.Run();
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning",
      "System.Net.Http.HttpClient": "Warning",
      "Orders.Payments": "Information"
    }
  }
}
// Hot path: source-generated, checks IsEnabled first, no boxing.
namespace Orders.Payments;

public static partial class PaymentLog
{
    [LoggerMessage(EventId = 2001, Level = LogLevel.Warning,
        Message = "Payment capture retry {Attempt} for order {OrderId}")]
    public static partial void CaptureRetry(this ILogger logger, int attempt, Guid orderId);
}

⚠ Common mistakes

  • Mistake: Logging the same exception in the repository, the service and the controller. Why it is wrong: One failure becomes three stack traces, tripling volume and confusing counts. Instead: Let it bubble and log once where it is handled, with context.
  • Mistake: Leaving Debug on in production "just in case". Why it is wrong: Volume and cost multiply, Debug lines cost CPU on hot paths, and they often contain payloads with personal data that then sit in retention. Instead: Enable Debug per category for a time box through runtime configuration, with an owner who turns it off.
  • Mistake: Logging every rejected request (a 400 from model validation) at Error. Why it is wrong: Client input errors are expected outcomes of a working service, so the error rate stops meaning "we are broken" and alerts fire on normal traffic. Instead: Log them at Information or Debug (or just count them as a metric), use Warning when the pattern is suspicious (a spike from one client, possible misuse), and keep Error for failures the service itself must fix. A validation failure inside your own processing, such as bad data from an upstream system, can be a real Error.
  • Mistake: Changing App Service app settings to raise a log level. Why it is wrong: It restarts the app, which can hide the very problem you are chasing. Instead: Use reloadable configuration or Azure App Configuration.
  • Mistake: Logging inside per-item loops at Information. Why it is wrong: A batch of 100,000 items becomes 100,000 lines. Instead: Log a summary with counts, and sample or rate-limit per-item logs.
  • Mistake: String interpolation in log calls on hot paths. Why it is wrong: The string is built even when the level is disabled and properties are lost. Instead: Use message templates or [LoggerMessage].
  • Mistake: No alert on ingestion volume. Why it is wrong: A flood is discovered on the invoice. Instead: Alert on GB per hour per table and set a daily cap as a last resort.
  • Mistake: Treating the level policy as fixed forever. Why it is wrong: Services change, and levels that were right at launch become noisy or blind. Instead: Review levels after incidents ("did we have the logs?") and in a periodic cost review, and keep retention aligned with what each level contains.

🏛 Senior insight: trade-offs

A log level policy is a team agreement more than a configuration file. Seniors write it down, enforce it in code review and give the on-call engineer a safe, audited way to turn detail up for one component and back down again. The framework already provides most of it: category filters, IOptionsMonitor reloads, the [LoggerMessage] generator and sampling and buffering in Microsoft.Extensions.Telemetry.

Technique When it fits Cost When not to
Static levels in config Small, stable services None When you debug live often
Runtime levels via App Configuration Many services, on-call needs live detail Small App Configuration cost Without a revert habit
Probabilistic sampling High-volume healthy traffic May miss rare Information events Audit or business events that must all be kept
Per-request buffering Need context only for failures Memory per request Very long-running requests

I measure success by GB per service per day, the share of Error logs that led to an action, and whether incident reviews ever said "we didn't have the logs".

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions per-category filters in appsettings.json Why: Checks the basics of categories and filters
    How to answer

    ILogger<T> is the logging abstraction from Microsoft.Extensions.Logging. You inject it, and the category is the full name of T, so every log line says which class wrote it.

    Each call has a level: Trace, Debug, Information, Warning, Error, Critical (and None to turn a category off). In appsettings.json the Logging:LogLevel section sets a minimum level per category prefix: Default for everything, and more specific prefixes like Microsoft.AspNetCore override it, the longest matching prefix wins. Providers can have their own overrides (Logging:Console:LogLevel).

    The trade-off: verbose levels help diagnose problems but cost money and noise, so production usually runs at Information with framework categories at Warning.

  2. When: Candidate mentions LoggerMessage or logging overhead Why: Checks hot-path logging cost
    How to answer

    A normal call like logger.LogDebug("Item {Id} took {Ms}", id, ms) goes through LoggerExtensions: it allocates a params object[], boxes the int and double, and does that even when Debug is off. The [LoggerMessage] source generator turns a partial method into a strongly typed one: it checks IsEnabled first, uses a cached, pre-parsed template, and passes values without boxing, so a filtered call allocates zero bytes and costs close to nothing (around a nanosecond on typical hardware; benchmark on yours, since absolute numbers vary by CPU and runtime). It also checks at compile time that placeholders match parameters.

    You still guard with IsEnabled when computing an argument is expensive, because arguments are evaluated before the call.

    The trade-off: more code per event, so use it for hot paths, libraries and your main event catalogue, not every one-off line.

  3. When: Candidate mentions the bill or ingestion alerts Why: Checks cost investigation once a flood has happened
    How to answer

    First measure, don't guess: in Log Analytics run union * | summarize sum(_BilledSize) by itemType, then break traces down by category and message template (OriginalFormat). One or two sources usually dominate: a Debug level left on, EF Core SQL command logging, HTTP body logging, health probes, or two pipelines sending the same data.

    Latency rises because logging runs on the request thread: synchronous sinks, a full console queue, or formatting large payloads.

    Fix in order: levels per category (configuration, no deploy), remove duplicates and noise, sample traces while keeping metrics complete, then workspace controls: daily cap as a safety net, cheaper table plans, retention, and a cost anomaly alert. The trade-off: every gigabyte you cut must not be the one you need at 3 a.m.

🛠 Real-world problems: how you handle them

An outage turned into a log flood that slowed the API
Situation
An order worker and API shared [a Container App] processing [8,000] messages per minute; the payment provider started timing out on a [Friday evening].
Signals
Azure Monitor alert on Log Analytics ingestion ([30 GB] in two hours), API p99 rising from [120 ms] to [900 ms], dotnet-counters showing high allocation rate and GC time.
Investigation
Ran KQL on AppExceptions grouped by ProblemId and OperationId and saw each failure logged three times. dotnet-counters and a dotnet-trace showed time in exception formatting and the exporter batch processor. The OpenTelemetry exporter reported dropped items.
Resolution
Immediate: raised the worker's category to Error via Azure App Configuration and opened the circuit breaker on the payment client. Long-term: logged exceptions once at the handler, added sampling for repeated errors and moved hot-path logs to `[LoggerMessage]`.
Prevention
A logging policy in the engineering handbook, a code review checklist item for duplicate exception logging, an hourly ingestion alert per table and a load test with the dependency failing.

How to tell it (STAR)

**S:** When our payment provider started timing out, our worker logged every failure three times and the API next to it slowed to [900 ms] p99. **T:** As [on-call lead], I had to stabilise it and stop it happening again. **A:** I raised the log level for the worker through App Configuration without a restart, opened the circuit breaker, then changed the code to log once at the boundary, sample repeated errors and use source-generated logging on hot paths. **R:** In the next provider outage, log volume was [95%] lower and API latency stayed under [150 ms].

↩ Usually asked after

More in Log Management

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me