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


⚡ 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?

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.

🤖 AlgoLassi Assistant Have a question about this tutorial?

Ask AlgoLassi and get an answer plus the tutorials worth studying next.

Ask a question

đŸ’Ŧ Comments

Sign in with Google to publish immediately, or comment anonymously and wait for approval.

Comments will appear here when available.