Introduction
When ShopNest checkout fails at 2 AM, logs tell you why. ASP.NET Core ships with ILogger<T>; production apps add Serilog for structured logs to files, Seq, or Application Insights.
After this article you will
- Use log levels appropriately
- Write structured logs with message templates
- Configure Serilog sinks and enrichers
- Add correlation IDs per request
- Mask sensitive data in log output
Prerequisites
- Article 26 — Filters
- ShopNest.Web with EF Core from Module 2
Concept deep-dive
| Level | Use when |
|---|---|
| Trace/Debug | Local debugging only |
| Information | Normal flow — order placed, payment started |
| Warning | Recoverable — retry, validation fail |
| Error | Exception, payment gateway down |
| Critical | App unusable — DB unreachable |
// Structured — DO NOT string interpolate for production analytics
_logger.LogInformation("Order {OrderId} paid {Amount} by {UserId}",
order.Id, order.Total, userId);
// Serilog Program.cs
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(builder.Configuration)
.Enrich.FromLogContext()
.Enrich.WithProperty("App", "ShopNest")
.WriteTo.Console()
.WriteTo.File("logs/shopnest-.txt", rollingInterval: RollingInterval.Day)
.CreateLogger();
builder.Host.UseSerilog();
Correlation ID: middleware sets TraceIdentifier or custom header — flows through all logs for one request.
Masking: never log full card numbers, passwords, or JWT tokens.
Hands-on — ShopNest Production E-Commerce Monitoring
- Add Serilog NuGet + appsettings Serilog section.
- CorrelationIdMiddleware pushes ID into LogContext.
- PaymentService logs Information on success, Error on gateway exception.
- Filter appsettings: Microsoft.EntityFrameworkCore at Warning in Production.
Common errors & best practices
- LogInformation for every loop iteration — noise and cost.
- String interpolation in logs — loses structured properties.
- Sync file writes under load — Serilog async sink helps.
Interview questions
Q: Structured logging benefit?
A: Query logs by OrderId, UserId in Seq/App Insights — not grep plain text.
Q: Serilog vs built-in?
A: Built-in abstracts providers; Serilog is rich sink/enricher ecosystem.
Q: Correlation ID purpose?
A: Tie all log lines from one HTTP request together in distributed traces.
Summary
- ILogger with structured templates is the baseline
- Serilog sinks feed files, Seq, Application Insights
- Correlation IDs essential for production debugging
- Mask PCI/PII — never log secrets
Previous: Filters
Next: Error Handling and Exception Management
FAQ
NLog instead of Serilog?
Both work — Serilog more common in .NET Core tutorials and microservices.
Log EF SQL in production?
Usually Warning only — Information SQL logs are verbose and costly.