loading experience

.NET

Structured logging in .NET with LoggerMessage

Fast, queryable logs: named placeholders and logging methods generated by the compiler.

Structured logging in .NET with LoggerMessage

A good log entry is not a sentence: it is an event with queryable data. ILogger supports structured logging, which keeps the text and the values separate.

Values stay queryable fields, not text to search.
Values stay queryable fields, not text to search.

Placeholders, not interpolation

// Avoid: the value is lost inside the string, and the string is always built
log.LogInformation($"Order {order.Id} created by {user}");

// Correct: Id and User stay separate, queryable fields
log.LogInformation("Order {OrderId} created by {User}", order.Id, user);

In log collection systems you can then search for "all events with OrderId = 4521" instead of searching text.

LoggerMessage: logs generated at compile time

For frequent log entries, the LoggerMessage attribute generates optimised methods that avoid allocations and check at compile time that placeholders match the parameters.

public static partial class Log
{
    [LoggerMessage(EventId = 1001, Level = LogLevel.Information,
        Message = "Order {OrderId} created for {Amount} euros")]
    public static partial void OrderCreated(this ILogger logger, int orderId, decimal amount);

    [LoggerMessage(EventId = 1002, Level = LogLevel.Warning,
        Message = "Payment declined for order {OrderId}: {Reason}")]
    public static partial void PaymentDeclined(this ILogger logger, int orderId, string reason);
}

log.OrderCreated(order.Id, order.Total);

Levels and noise

  • Information for meaningful business events.
  • Warning for unusual but handled situations.
  • Error for failed operations, always with the exception as the first argument.
  • Debug for details, disabled in production.

And never personal data or secrets in logs: passwords, tokens and sensitive data must not end up in a file that many people can read.

Comments (0)

No comments yet.

Leave a comment