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.
I treat log levels as a contract the whole team follows:
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.
"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.AspNetCoreandSystem.Net.Http.HttpClientat 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 aLoggingLevelSwitch. 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."
| 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 |
| 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 |
| 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 |
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.
Checks whether the candidate runs logging deliberately in production: clear level semantics, safe runtime changes and protection against floods.
Green flags
Red flags
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.
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.
The Microsoft.Extensions.Telemetry package (from the .NET 9 era onwards) adds:
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.
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.
Logging:LogLevel in appsettings.json while the app runs and confirm new Debug lines appear without a restart.logger.LogInformation("x {A}", 42) vs a [LoggerMessage] method with BenchmarkDotNet when the level is disabled.AddRandomProbabilisticSampler(0.1, LogLevel.Information) and count lines in Seq before and after.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);
}
[LoggerMessage].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".
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.
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.
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.
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].
Last updated 23 Nov 2026.