ASP.NET Core Interview Question #158

How should exceptions be logged in ASP.NET Core?

Logging, Error Handling & Background Services Mid-Level Intermediate

Quick Interview Answer

When an exception is logged, pass the Exception object to the logging method so the provider can record its type, message, stack trace, and inner-exception information.

Detailed Explanation

When an exception is logged, pass the Exception object to the logging method so the provider can record its type, message, stack trace, and inner-exception information.

Log an exception at the layer that can add meaningful context or where it is ultimately handled. Repeatedly logging the same exception at every layer creates noise and can make incidents harder to analyze.

Never expose detailed exception information directly to production users. User-facing responses and internal diagnostic logs have different purposes.

Code Example

try
{
    await _paymentService.ChargeAsync(order);
}
catch (PaymentException ex)
{
    _logger.LogError(
        ex,
        "Payment failed for order {OrderId}",
        order.Id);

    throw;
}