A real-world logging cost and latency incident: finding ingestion sources with KQL over _BilledSize by table, category and template, common causes (Debug left on, EF Core command logging, HTTP body logging, duplicate pipelines, health-check noise, disabled sampling), latency from synchronous or blocked log writes, fixes in levels, filters, sampling and sinks, and long-term controls such as daily caps, table plans, transformations and cost alerts.
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.
"I'd treat it as an incident with two symptoms and probably one cause. The first thing is data, not opinions: Log Analytics records the billed size of every row, so
union * | summarize sum(_BilledSize) by itemTypetells me whether it's traces, requests, dependencies or exceptions, and then I grouptracesby category name and message template, and by cloud role, over the last 30 days to see when it jumped. Almost always one or two sources are most of the bill, and the jump lines up with a deployment or a configuration change.For example, at [company] the bill went from about [A$4,000 to A$12,000] a month. The KQL showed [70%] of ingestion was
Microsoft.EntityFrameworkCore.Database.Commandat Information plus our own Debug lines: someone had setLogging__LogLevel__Default=Debugon the production App Service to investigate a bug and never removed it. The latency was the same cause: at that volume the console provider's queue was filling, and the defaultWaitmode blocked request threads. I set the level back through configuration, which took effect without a deploy, then over the next sprint removed a duplicate Serilog Application Insights sink, filtered health probes, and set explicit trace sampling. Ingestion dropped by [about 75%] and p95 latency went back to [120] ms.The mistake I see is reaching for the daily cap first. A cap stops the bill by stopping all ingestion, so the day you have an incident is the day you have no logs. I use a cap only as a safety net set well above normal, and fix the sources. Then I make it stay fixed: an ingestion anomaly alert, temporary verbose logging with an expiry, and telemetry config changes reviewed like code. Cost is a logging quality metric: noise you pay for is noise that hides signal."
| Cause | How it shows in KQL | Fix |
|---|---|---|
| Default or category at Debug in prod | Huge traces count at severityLevel 0–1 |
Reset level in config; time-box verbose logging |
EF Core Database.Command at Information |
Category Microsoft.EntityFrameworkCore.Database.Command dominates |
Set to Warning; use Query Store for slow SQL |
| HTTP logging with bodies | Large _BilledSize per row from Microsoft.AspNetCore.HttpLogging |
Headers allowlist, no bodies |
| Health probes traced and logged | requests named GET /healthz dominate |
Filter probes in instrumentation and logging |
| Duplicate pipelines (SDK + Serilog sink) | Identical messages twice per operation | Keep one pipeline |
| Sampling off | itemCount always 1 |
Distro TracesPerSecond / SamplingRatio |
| Chatty dependency telemetry (Redis, blob per call) | dependencies table dominates |
Sampling, filter dependency types |
| Mechanism | Detail |
|---|---|
| Console queue full | Console provider queues to a background thread; when the queue is full, the default QueueFullMode.Wait blocks callers |
| Synchronous sinks | File or HTTP sink writing on the request thread |
| Formatting large objects | Serialising DTOs or bodies for every request |
| Exporter back-pressure | Very high volume increases CPU and GC in batching exporters |
After the fixes, monthly ingestion went from about [900] GB to [210] GB, the bill from [A$12,000] to [A$3,100], and p95 latency from [310] ms back to [120] ms; an anomaly alert on daily ingestion has fired [twice] since, both times catching a forgotten Debug override within a day.
Checks whether the candidate can run a cost and performance investigation with data, fix it without losing incident visibility, and put guardrails in place.
Green flags
_BilledSize by table, category and template.Red flags
Workspace-based Application Insights stores data in Log Analytics tables (AppTraces, AppRequests, AppDependencies, AppExceptions, AppMetrics; the classic names traces, requests work in the Application Insights blade). You pay mainly per GB ingested (pay-as-you-go or a commitment tier), plus retention beyond the included period. Every row carries _BilledSize in bytes.
ILogger / Activity / Meter
│
▼
provider filters (levels) ──► sampler ──► exporter batch ──► ingestion endpoint
↑ cheapest place to cut ↑ traces only │
▼
transformation (DCR, where supported) ──► table
│
plan: Analytics / Basic / Auxiliary
retention per table
Cut as early as possible: a log filtered by level costs nothing downstream; a log dropped by an ingestion-time transformation has already cost CPU, network and exporter time.
// Which table?
union withsource = Table *
| where TimeGenerated > ago(30d)
| summarize GB = sum(_BilledSize) / 1e9 by Table
| order by GB desc
// Which category and template inside traces?
AppTraces
| where TimeGenerated > ago(7d)
| summarize GB = sum(_BilledSize) / 1e9, Rows = count()
by Category = tostring(Properties.CategoryName), Template = tostring(Properties.OriginalFormat), AppRoleName
| top 20 by GB
// When did it start?
AppTraces
| where TimeGenerated > ago(30d)
| summarize GB = sum(_BilledSize) / 1e9 by bin(TimeGenerated, 1d), AppRoleName
| render timechart
The property names depend on the SDK or exporter version; check one row first.
The console logger formats on the caller's thread and enqueues the text for a background writer. stdout in containers is often slow (a pipe read by the container runtime). With very high volume the queue fills, and with ConsoleLoggerQueueFullMode.Wait (the default) the request thread waits. DropWrite avoids blocking but loses lines. The real fix is less volume.
Sampling reduces requests, dependencies and their logs (with trace-based log sampling in recent Azure Monitor exporters), but logs written outside a sampled trace, start-up and background loops, aren't affected. Metrics stay accurate because they are pre-aggregated. Sampled rows carry itemCount so counts in the portal are scaled back up.
Raise a category through Azure App Configuration with a label and a reminder, or use a dynamic LoggingLevelSwitch exposed on an admin endpoint that reverts after N minutes. Never set production-wide Debug through a portal app setting without an expiry.
k6 at Debug and at Information, and compare ingestion and p95 latency.MaxQueueLength to a small number and observe request latency at high log volume with Wait versus DropWrite.TracesPerSecond = 1 and verify itemCount scaling in the requests table.Usage table or a log search alert on _BilledSize.The changes that typically fix this, in configuration and code.
// appsettings.Production.json: levels per category, no Debug by default
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning",
"Microsoft.EntityFrameworkCore": "Warning",
"Microsoft.EntityFrameworkCore.Database.Command": "Warning",
"System.Net.Http.HttpClient": "Warning"
},
"Console": {
"LogLevel": { "Default": "Warning" }
}
}
}
// Program.cs
using Azure.Monitor.OpenTelemetry.AspNetCore;
using OpenTelemetry.Instrumentation.AspNetCore;
var builder = WebApplication.CreateBuilder(args);
builder.Logging.ClearProviders();
builder.Logging.AddJsonConsole();
// One pipeline to Application Insights (no extra Serilog sink, no classic SDK)
builder.Services.AddOpenTelemetry().UseAzureMonitor(o =>
{
o.TracesPerSecond = 5; // explicit sampling decision, documented in an ADR
});
// Don't trace or log health probes: they were [30%] of requests
builder.Services.Configure<AspNetCoreTraceInstrumentationOptions>(o =>
o.Filter = ctx => !ctx.Request.Path.StartsWithSegments("/healthz"));
var app = builder.Build();
app.MapGet("/healthz", () => TypedResults.Ok());
app.MapGet("/orders/{id:guid}", (Guid id, ILogger<Program> logger) =>
{
logger.LogDebug("Loading order {OrderId}", id); // filtered out in production
return TypedResults.Ok(new { id });
});
app.Run();
# Remove the forgotten override that caused the spike (App Service)
az webapp config appsettings delete --name orders-api --resource-group rg-orders-prod \
--setting-names Logging__LogLevel__Default
_BilledSize by table, category and template.dotnet-trace and check console queue and sink behaviour.A telemetry bill is a design review in disguise. It tells you which code is noisy, which levels nobody agreed, and which configuration changes bypass review. I fix the immediate spike quickly through configuration, then put three guardrails in place: an ingestion anomaly alert, a written logging-level policy, and a rule that verbose overrides expire. I also keep the conversation about value: if a table costs A$2,000 a month and nobody queried it in 90 days, it goes to a cheaper plan or away.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Category level changes | First fix, always | None | – |
| Trace sampling | High request volume | Fewer individual traces | Low-traffic services where every trace matters |
| Basic/Auxiliary table plans | Verbose data rarely queried | Limited queries, per-query charge | Data used in alerts and dashboards |
| Ingestion transformations | Legacy apps you can't change quickly | Data already sent; rules to maintain | As a substitute for fixing the code |
| Daily cap | Safety net only | Blind spot when hit | Primary cost control |
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.
OpenTelemetry gives you three correlated signals: traces (a span per operation, linked by trace id), metrics (cheap aggregated counters and histograms) and logs (events that carry the TraceId and SpanId of the span they were written in).
In .NET the runtime already emits Activity and Meter data; you call AddOpenTelemetry() with WithTracing, WithMetrics and WithLogging, set a resource (service.name), and choose an exporter: UseOtlpExporter() for any OTLP back end or Collector (endpoint from OTEL_EXPORTER_OTLP_ENDPOINT or options), or the Azure Monitor distro (UseAzureMonitor()) for Application Insights.
For cost: metrics for rates and latency (never sampled), sampled traces (the distro now defaults to a rate-limited sampler of 5 traces per second, which adapts the kept percentage to load; you can change the rate or switch to a fixed SamplingRatio), level-filtered logs, and tail sampling in a Collector, configured with policies to keep errors and slow traces. The trade-off is completeness versus ingestion cost.
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.
How to tell it (STAR)
**S:** At [company] our orders API's Application Insights bill tripled to about [A$12,000] a month, and at the same time p95 latency went from [120] to [310] ms. **T:** I was asked to bring the cost down quickly without losing the telemetry we relied on for incidents, and to explain the latency. **A:** I used KQL on billed size by table, category and template and found most of it was EF Core SQL logging and Debug lines, which started the day someone set a Debug override in the portal. A dotnet-trace capture showed request threads waiting on the console logger at that volume, and a duplicate Serilog sink doubling traces. I removed the override straight away, then cleaned up the duplicate pipeline, probe noise and sampling, and added an ingestion anomaly alert and an expiry rule for verbose logging. **R:** Ingestion fell by [about 75%], the bill dropped to around [A$3,100], p95 went back to [120] ms, and the alert has since caught [two] forgotten overrides within a day.
Last updated 23 Nov 2026.