Logging and observability
Logging and observability tell you what happened inside a running app: which order failed, why, and where a request spent its time. In ASP.NET Core this means ILogger with structured logs, level filters, HTTP request logs, Serilog sinks and OpenTelemetry traces.
43.1 Why is it used?
- In production you cannot attach a debugger; logs and traces are the only way to see what happened.
- Structured fields (OrderId = 13) let log tools search and filter instead of grepping text.
- Levels separate errors from normal events and keep noise out.
- Traces show where a request went and how long each step took.
43.2 The bug: Console.WriteLine
C#
app.MapPost("/orders/{id:int}", (int id) =>{ Console.WriteLine($"Order {id} placed"); if (id == 13) Console.WriteLine($"Payment failed {id}"); return Results.Ok(new { id });});Output
$ curl -X POST localhost:5043/orders/101$ curl -X POST localhost:5043/orders/13# server consoleOrder 101 placedOrder 13 placedPayment failed 13- No level: the payment failure looks exactly like an info line.
- No category: you cannot tell which class wrote the line.
- Data inside the text: OrderId cannot be searched as a field.
- Step 1
1.No level: error looks like info
- Step 2
2.No category: which class?
- Step 3
3.Data inside text: can't search OrderId
- Step 4
4.Needed: level + category + fields = ILogger
43.3 Fix: ILogger<T>
C#
var builder = WebApplication.CreateBuilder(args);var app = builder.Build(); app.MapPost("/orders/{id:int}", (int id, ILogger<Program> logger) =>{ logger.LogInformation( "Order {OrderId} placed", id); if (id == 13) logger.LogError( "Payment failed for {OrderId}", id); return Results.Ok(new { id });}); app.Run();Output
$ curl -X POST localhost:5043/orders/101$ curl -X POST localhost:5043/orders/13# server consoleinfo: Program[0] Order 101 placedinfo: Program[0] Order 13 placedfail: Program[0] Payment failed for 13- ILogger<Program> is injected through DI; Program becomes the category.
- LogInformation takes a message template: {OrderId} is a named placeholder and id is a separate argument.
- LogError for the failed payment; the console now shows info/fail levels and the Program category.
43.4 Structured logs: JSON console
C#
var builder = WebApplication.CreateBuilder(args);builder.Logging.ClearProviders();builder.Logging.AddJsonConsole();Output
$ curl -X POST localhost:5043/orders/101# server console{ "LogLevel": "Information", "Category": "Program", "Message": "Order 101 placed", "State": { "OrderId": 101, "{OriginalFormat}": "Order {OrderId} placed" } }- ClearProviders removes the default providers; AddJsonConsole makes every log a JSON object.
- OrderId 101 is a separate field inside State, so tools can filter: all logs where OrderId = 13.
43.5 Log levels
| Level | Console tag | Use for |
|---|---|---|
| Trace | trce | Very fine detail during development |
| Debug | dbug | Development detail (e.g. cart loaded) |
| Information | info | Normal events (order placed) |
| Warning | warn | Something unexpected, app keeps running |
| Error | fail | An operation failed (payment failed) |
| Critical | crit | The whole app is at risk |
- There is a minimum level; logs below it are not written at all.
43.6 Checkpoint: how many lines?
C#
app.MapGet("/cart/{id:int}", (int id, ILogger<Program> logger) =>{ logger.LogDebug("Cart {CartId} loaded", id); logger.LogInformation( "Cart {CartId} viewed", id); return Results.Ok(new { id, items = 3 });});Output
$ curl localhost:5043/cart/7{"id":7,"items":3}# server consoleinfo: Program[0] Cart 7 viewed- Default level in appsettings is Information; Debug is below it, so the filter drops "Cart 7 loaded" before it is written. Only one line appears.
43.7 Filters in appsettings.json
JSON
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning", "Program": "Debug" } }, "AllowedHosts": "*"}Output
$ curl localhost:5043/cart/7# server consoledbug: Program[0] Cart 7 loadedinfo: Program[0] Cart 7 viewed- Default: Information applies to every category.
- Microsoft.AspNetCore: Warning cuts framework noise.
- Program: Debug turns on debug logs only for our class; the most specific category rule wins.
43.8 HTTP logging middleware
C#
using Microsoft.AspNetCore.HttpLogging; var builder = WebApplication.CreateBuilder(args);builder.Services.AddHttpLogging(options =>{ options.LoggingFields = HttpLoggingFields.RequestMethod | HttpLoggingFields.RequestPath | HttpLoggingFields.ResponseStatusCode | HttpLoggingFields.Duration; options.CombineLogs = true;});var app = builder.Build();app.UseHttpLogging();Output
$ curl -X POST localhost:5043/orders/101# server consoleinfo: Microsoft.AspNetCore.HttpLogging .HttpLoggingMiddleware[9] Request and Response: Method: POST Path: /orders/101 StatusCode: 200 Duration: 87.497- AddHttpLogging chooses the fields: method, path, status code, duration.
- CombineLogs = true puts request and response into one entry.
- It writes at Information, so the HttpLogging category needs Information in appsettings.
43.9 Serilog: sinks + request logging
C#
using Serilog;using Serilog.Events; var builder = WebApplication.CreateBuilder(args);builder.Services.AddSerilog(config => config .MinimumLevel.Information() .MinimumLevel.Override("Microsoft", LogEventLevel.Warning) .WriteTo.Console() .WriteTo.File("logs/shop-.txt", rollingInterval: RollingInterval.Day)); var app = builder.Build();app.UseSerilogRequestLogging();Output
$ dotnet add package Serilog.AspNetCoreinfo : PackageReference for package 'Serilog.AspNetCore' version '10.0.0' added $ curl -X POST localhost:5043/orders/101# server console[01:34:25 INF] Order 101 placed[01:34:25 INF] HTTP POST /orders/101 responded 200 in 232.5861 ms$ cat logs/shop-20261107.txt2026-11-07 01:34:25.718 +05:30 [INF] Order 101 placed- Serilog sinks send logs to the console, files, Seq or cloud tools.
- MinimumLevel.Override("Microsoft", Warning) quiets the framework.
- WriteTo.File with RollingInterval.Day creates a new file every day (shop-20261107.txt).
- UseSerilogRequestLogging writes one clean summary line per request.
43.10 OpenTelemetry: traces
C#
using OpenTelemetry.Resources;using OpenTelemetry.Trace; var builder = WebApplication.CreateBuilder(args);builder.Services.AddOpenTelemetry() .ConfigureResource(resource => resource.AddService("shop-api")) .WithTracing(tracing => tracing .AddAspNetCoreInstrumentation() .AddConsoleExporter()); var app = builder.Build();Output
$ curl -X POST localhost:5043/orders/101# server consoleActivity.TraceId: 6bd098a193bbdfd58fd1484df6238d1bActivity.SpanId: 086880e8c646ed07Activity.DisplayName: POST /orders/{id:int}Activity.Duration: 00:00:00.3396324 http.route: /orders/{id:int} http.response.status_code: 200Resource associated with Activity: service.name: shop-api- Logs say what happened; traces say where a request went and how long it took.
- AddAspNetCoreInstrumentation creates a span for every request; AddService("shop-api") sets the service name.
- TraceId identifies one complete request; DisplayName is the route; Duration is the time; tags hold the status code.
- The console exporter is for learning only; in production use the OTLP exporter to Jaeger, Grafana or a cloud tool.
- Step 1
1.Code writes an event through ILogger
- Step 2
2.Filters check level + category
- Step 3
3.Providers / Serilog sinks write to console, file, JSON
- Step 4
4.OpenTelemetry adds traces and ships to an observability tool
Code only knows ILogger; the destination comes from config
43.11 Comparison: logging options
| Option | What you get | When |
|---|---|---|
| Console.WriteLine | Plain text, no level/category | Never in an app |
| ILogger<T> (built-in) | Levels, categories, message templates | Always: the base API |
| AddJsonConsole | Structured JSON with State fields | Containers, log collectors |
| UseHttpLogging | Per request method/path/status/duration | Request auditing |
| Serilog | Many sinks, rolling files, request summary | Teams needing files/Seq/cloud |
| OpenTelemetry | Traces (spans) + OTLP export | Distributed tracing in production |
43.12 Common mistakes
- String interpolation in a log call: the message becomes a fixed string, the OrderId field disappears and the string is built even when the level is filtered out.
- Logging everything at Information: bigger storage bill and the real error is lost in noise.
- Logging sensitive data (passwords, OTPs, card numbers); enable body/header HTTP logging only with care.
C#
// Wrong: interpolation, OrderId field is gonelogger.LogInformation( $"Order {id} placed");// State: { "{OriginalFormat}": "Order 101 placed" } // Right: message template, OrderId is a searchable fieldlogger.LogInformation( "Order {OrderId} placed", id);// State: { "OrderId": 101,// "{OriginalFormat}": "Order {OrderId} placed" }43.13 Logging rules
- Inject ILogger<T>, not Console.WriteLine.
- Message template, not interpolation.
- Production: Default Information, framework Warning.
- Never log sensitive data.
- Send logs and traces to one central tool (OpenTelemetry / Serilog).
43.14 Interview tips
- I inject ILogger<T>, so the category comes from the class name.
- I write structured logs with message templates, so values like OrderId become searchable fields.
- Levels and appsettings filters (most specific category wins) control noise.
- For tracing I add OpenTelemetry instrumentation and export via OTLP to a central tool.