Recipe 4.1 · C#
ILogger and Message Templates
Problem
Log lines are built with string concatenation or interpolation. They read fine to a human, but a log search tool sees only text. You cannot ask "show me every failure for order 48213" or "how many payments over $10,000 failed today" without regular expressions and luck.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
// Not this: the values are baked into the text.
public void Process(Order order)
{
Logger.Write("Processing order " + order.Id + " for " +
order.Total.ToString("C"));
try
{
_gateway.Charge(order);
}
catch (Exception ex)
{
Logger.Write($"Error processing order {order.Id}: {ex.Message}");
}
}
The improved recipe
Inject ILogger<T> and pass values as arguments to a message template. For hot paths and for
messages you want to catalog, use the LoggerMessage source generator.
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
namespace ImproveCode.Logging;
public sealed record Order(int Id, string CustomerId, decimal Total);
public interface IPaymentGateway
{
Task ChargeAsync(Order order, CancellationToken ct);
}
public sealed class OrderProcessor(
IPaymentGateway gateway,
ILogger<OrderProcessor> logger)
{
public async Task<bool> ProcessAsync(
Order order, CancellationToken ct)
{
logger.ProcessingOrder(order.Id, order.CustomerId, order.Total);
try
{
await gateway.ChargeAsync(order, ct);
logger.LogInformation(
"Order {OrderId} charged successfully", order.Id);
return true;
}
catch (TimeoutException ex)
{
logger.PaymentFailed(ex, order.Id, order.Total);
return false;
}
}
}
internal static partial class OrderLog
{
[LoggerMessage(EventId = 1001, Level = LogLevel.Information,
Message = "Processing order {OrderId} for customer " +
"{CustomerId}, total {Total}")]
public static partial void ProcessingOrder(
this ILogger logger, int orderId, string customerId,
decimal total);
[LoggerMessage(EventId = 1002, Level = LogLevel.Error,
Message = "Payment failed for order {OrderId}, total {Total}")]
public static partial void PaymentFailed(
this ILogger logger, Exception ex, int orderId, decimal total);
}
How it works
A message template looks like a format string, but the names in braces are property names, not
positions. When the provider supports structured logging, {OrderId} becomes a field named
OrderId with the value 48213, stored alongside the rendered text. Your log store can then
filter, group and chart on it. The rendered message still reads naturally for humans.
The exception goes in the first parameter, not into the message. Every provider knows how to
write the full exception, including the stack trace and inner exceptions. ex.Message alone
throws away the most useful part.
ILogger<OrderProcessor> sets the category to the full type name. That gives you per-namespace
filtering in configuration (for example, Warning for Microsoft.AspNetCore, Debug for your
own data layer while you chase a bug) without touching code.
The [LoggerMessage] attribute tells the compiler to generate the method body. The generated code
checks IsEnabled before doing any work, avoids boxing the value types, and parses the template
once at compile time. It also gives each message a stable EventId, which operations teams love:
an alert rule on event 1002 survives any rewording of the text.
Variations and pitfalls
- Never interpolate into a template:
LogInformation($"Order {id}")compiles and runs, but it produces a new template for every value and loses the property. The CA2254 analyzer warns about this; turn it on. - Keep property names consistent across the code base. If one class logs
{OrderId}and another logs{OrderNo}, your query needs both. A short list of standard names in the team wiki pays off quickly. - Pick levels deliberately.
Informationis for events an operator wants to see in a normal day (job started, job finished, order placed).Debugis for developers.Warningmeans something unexpected happened but the app recovered.Errormeans an operation failed.Criticalmeans the process or a whole feature is down. - Don't guard every call with
if (logger.IsEnabled(...)). The extension methods already check. Guard only when computing an argument is expensive. - Format specifiers work:
{Total:C}renders as currency in the text while the property keeps the raw number.