Diagnosing a production failure is difficult when the only available message says that “something went wrong.” If logs cannot be connected to a request, user action, or business operation, engineers spend valuable time searching through unstructured text. ASP.NET Core’s ILogger infrastructure supports structured logging, which records important values as named fields instead of embedding everything into one finished string.
This guide explains message templates, logging scopes, EventId, JSON console output, and practical ways to control logging noise and cost. The goal is not to record every line of execution. The goal is to produce events that help people and systems answer operational questions.
Why structured logging matters
A traditional log line might look like this:
Order 1842 was created for customer 73
A person can read the line, but a log analysis system benefits more when OrderId and CustomerId are separate properties. In ASP.NET Core, use named placeholders in a message template:
_logger.LogInformation( "Order {OrderId} was created for customer {CustomerId}", order.Id, order.CustomerId);
{OrderId} and {CustomerId} are not merely string-formatting tokens. Logging providers can preserve the named values as structured state. This makes queries such as OrderId = 1842 more reliable than searching a free-form message.
Use message templates instead of string interpolation
The following code loses the field-oriented structure:
_logger.LogInformation($"Order {order.Id} was created");
Keep the template static and pass values separately:
_logger.LogInformation( "Order {OrderId} was created", order.Id);
Consistent placeholder names are just as important as using templates. If one component calls a value Id and another calls the same concept OrderNumber, searches and dashboards become unnecessarily complicated. Establish conventions for identifiers, statuses, durations, and other frequently queried fields.
Choose log levels based on impact
A log level communicates the importance of an event and affects how providers filter it. Using the same level for every message makes useful signals harder to distinguish from noise.
| Level | Typical use |
|---|---|
| Trace | Highly detailed diagnostic information, usually enabled temporarily |
| Debug | Technical details useful during development or investigation |
| Information | Important events in a normal workflow |
| Warning | An unusual condition that does not stop the operation |
| Error | A failed operation or unexpected exception |
| Critical | A failure threatening the application or a core capability |
For example, a missing resource is not automatically an error. If a client requests an unknown identifier, that may be an expected condition and could be logged at Information or Warning. A database connection failure, however, normally deserves Error because it prevents an operation from completing.
Pass exceptions as exception parameters
Do not convert an exception into part of a formatted message. Pass it to the logging method:
try { await service.ProcessAsync(request, cancellationToken); } catch (Exception exception) { _logger.LogError( exception, "Payment processing failed for {PaymentId}", request.PaymentId); throw; }
This allows the provider to preserve the exception type, message, and stack trace in its normal representation. Avoid exposing secrets through exception messages or custom fields. Passwords, access tokens, payment card data, and unnecessary personal information should not be logged.
Add shared context with scopes
A request or business operation can produce several log entries. A scope associates those entries with common context. BeginScope starts a scope and returns an IDisposable that ends it when disposed.
public async Task<IResult> GetOrderAsync( Guid orderId, ILogger<OrdersEndpoint> logger, IOrderService service, CancellationToken cancellationToken) { using var scope = logger.BeginScope(new Dictionary<string, object> { ["OrderId"] = orderId, ["Operation"] = "GetOrder" }); logger.LogInformation("Order lookup started"); var order = await service.GetAsync(orderId, cancellationToken); if (order is null) { logger.LogWarning("Order was not found"); return Results.NotFound(); } logger.LogInformation("Order lookup completed"); return Results.Ok(order); }
Depending on the provider and configuration, logs inside the scope can carry the shared properties. For the console provider, scopes must be included in the formatter configuration if you want them displayed. Keep scopes short-lived and limited to a clear operation boundary. Long-lived or global scopes can accidentally attach the wrong context to later messages.
Enable JSON console output
JSON is generally more convenient than plain text when a log collector will parse the output. An ASP.NET Core application can configure the built-in JSON console formatter like this:
var builder = WebApplication.CreateBuilder(args); builder.Logging.AddJsonConsole(options => { options.IncludeScopes = true; options.TimestampFormat = "yyyy-MM-ddTHH:mm:ss.fffZ"; options.UseUtcTimestamp = true; options.JsonWriterOptions = new JsonWriterOptions { Indented = false }; }); var app = builder.Build();
Single-line JSON is often easier for production collectors to ingest. Do not serialize a log message to JSON yourself and then pass that string to the JSON provider. The logging infrastructure already performs serialization, and pre-serializing the message can result in double-encoded or difficult-to-query output. Supply values through message templates and scopes instead.
Use EventId to identify event types
EventId can distinguish important events within a component:
private static readonly EventId OrderCreated = new(1001, nameof(OrderCreated)); _logger.LogInformation( OrderCreated, "Order {OrderId} was created", order.Id);
Treat event identifiers as a stable operational contract. Reusing the same numeric identifier for unrelated meanings can make alerts and searches misleading. EventId is not required for every log message, but it can be valuable for important business and system events that need consistent filtering over time.
Balance diagnostic detail and runtime cost
Logging is part of application behavior. Excessive Information output increases storage and processing costs, while insufficient context makes incidents harder to investigate. If building a diagnostic value is expensive, check whether the level is enabled first:
if (_logger.IsEnabled(LogLevel.Debug)) { var diagnosticPayload = BuildDiagnosticPayload(); _logger.LogDebug("Diagnostic payload: {Payload}", diagnosticPayload); }
For frequently executed paths, consider .NET’s source-generated logging model. Methods decorated with LoggerMessageAttribute allow templates to be generated at compile time and can reduce some runtime overhead compared with repeatedly parsing extension-method calls. Use it where logging volume or allocation behavior justifies the additional structure.
A practical logging checklist
- Use message templates instead of string interpolation.
- Choose stable, descriptive placeholder names.
- Pass exceptions as exception parameters.
- Connect related events with request or operation scopes.
- Consider JSON output for machine-ingested production logs.
- Never log passwords, tokens, payment data, or unnecessary personal information.
- Select levels according to operational impact.
- Manage EventId values consistently for important event types.
- Measure log volume and improve fields before simply adding more messages.
Conclusion
Effective logging does not mean recording every internal step. It means making important events visible with enough context to search, correlate, and explain system behavior. ASP.NET Core’s ILogger infrastructure supports this approach through message templates, scopes, EventId, and JSON formatting without requiring a custom abstraction for basic scenarios.
Start by listing the questions your operations team needs to answer: Which request failed? Which order was affected? How often does the failure occur? Then design a small, consistent set of safe fields that answers those questions. The result will be logs that are easier to query, cheaper to manage, and more useful during real incidents.
0 Comments