ASP.NET Core Interview Question #156

What is structured logging?

Logging, Error Handling & Background Services Mid-Level Intermediate

Quick Interview Answer

Structured logging records named properties alongside a message template instead of building one long formatted string. Those properties can be indexed and queried by log-management systems.

Detailed Explanation

Structured logging records named properties alongside a message template instead of building one long formatted string. Those properties can be indexed and queried by log-management systems.

For example, OrderId and UserId can be stored as distinct fields, making it easier to search all events related to one order or request.

Message templates should generally be preferred over string interpolation for structured log calls because they preserve property names and avoid unnecessary formatting work when a log level is disabled.

Code Example

// Preferred structured logging
_logger.LogInformation(
    "Order {OrderId} completed for customer {CustomerId}",
    order.Id,
    order.CustomerId);

// Avoid relying only on interpolation:
// _logger.LogInformation($"Order {order.Id} completed");