ASP.NET Core Logging Basics: ILogger and Structured Logs
Good logging makes production problems much easier to diagnose. ASP.NET Core provides ILogger so application code can record useful information without depending directly on a particular logging provider.
đ§Š Inject ILogger
public class OrderService
{
private readonly ILogger<OrderService> _logger;
public OrderService(ILogger<OrderService> logger)
{
_logger = logger;
}
public void Process(int orderId)
{
_logger.LogInformation("Processing order {OrderId}", orderId);
}
}
đ Choose the Right Log Level
- Trace â very detailed diagnostic information.
- Debug â useful during development and troubleshooting.
- Information â normal application events.
- Warning â unexpected conditions that do not necessarily stop the request.
- Error â failures that need investigation.
- Critical â serious failures affecting the application.
⥠Use Structured Logging
Prefer named properties instead of building log messages with string concatenation.
_logger.LogInformation(
"User {UserId} updated product {ProductId}",
userId,
productId);
Structured properties make logs easier to search and analyze.
đ¨ Log Exceptions Correctly
try
{
await ProcessAsync();
}
catch (Exception ex)
{
_logger.LogError(ex, "Order processing failed for {OrderId}", orderId);
throw;
}
Passing the exception object preserves its details and stack trace for the configured logging provider.
đ§ Configure Log Levels
Log levels can be controlled through configuration so production environments do not have to emit excessive diagnostic output.
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
đ What Should You Log?
- Important business events.
- External service failures.
- Unexpected exceptions.
- Useful identifiers such as order or request IDs.
- Timing information for operations where performance matters.
Avoid logging passwords, tokens, access keys, and other sensitive information.
đ¯ Key Takeaway
Use ILogger with meaningful log levels and structured properties. Good logs should help you understand what happened, where it happened, and which operation was affected.
Continue with ⥠ASP.NET Core Tutorials.
Ask AlgoLassi and get an answer plus the tutorials worth studying next.
đŦ Comments
Sign in with Google to publish immediately, or comment anonymously and wait for approval.
Comments will appear here when available.