ASP.NET Core MVC Interview Question #134
How should logging be performed in an MVC controller or service?
Dependency Injection, Services, Error Handling, Logging & Performance Senior Advanced
Quick Interview Answer
Use ILogger<T> through dependency injection. Structured logging should use message templates with named properties rather than building log messages through string concatenation.
Detailed Explanation
Use ILogger<T> through dependency injection. Structured logging should use message templates with named properties rather than building log messages through string concatenation.
Log useful operational context without recording passwords, tokens, sensitive personal data, or other secrets. Choose log levels consistently so production logs remain actionable.
Code Example
private readonly ILogger<ProductsController> _logger;
public ProductsController(
ILogger<ProductsController> logger)
{
_logger = logger;
}
_logger.LogInformation(
"Viewing product {ProductId}", id);