Slider

How To Implement Logging in ASP.NET Core.

Learn how to implement logging in ASP.NET Core using ILogger and Serilog, with practical examples and best practices.

Logging is the process of recording application events so you can:

  • Debug issues
  • Monitor behavior
  • Trace requests
  • Audit actions in production

Without proper logging:

  • Bugs are hard to reproduce
  • Production failures are invisible
  • Root cause analysis becomes guesswork

ASP.NET Core has ILogger built in via Microsoft.Extensions.Logging. Supported Providers (by default)
  • Console
  • Debug
  • EventSource
  • Application Insights (Azure)
Rule: Never log everything as Information.

How To Use ILogger?

Step 1: Inject ILogger.
public class OrderController : ControllerBase
{
    private readonly ILogger<OrderController> _logger;

    public OrderController(ILogger<OrderController> logger)
    {
        _logger = logger;
    }
}

Step 2: Log Messages
_logger.LogInformation("Order creation started");

_logger.LogWarning("Order {OrderId} has no items", orderId);

_logger.LogError(exception, "Failed to create order {OrderId}", orderId);

Good Option 1: Logging Exception Correctly.
catch (Exception ex)
{
    _logger.LogError(ex, "Error while processing order {OrderId}", orderId);
    throw;
}
👉 Always pass the exception object to preserve stthe ack trace.

Good Option 2: Logging in Middleware.
public async Task InvokeAsync(HttpContext context)
{
    _logger.LogInformation(
        "Request {Method} {Path}",
        context.Request.Method,
        context.Request.Path);

    await _next(context);

    _logger.LogInformation(
        "Response {StatusCode}",
        context.Response.StatusCode);
}

Built-in logging is good, but Serilog is preferred in production because it provides:
  • Rich structured logging
  • Multiple sinks (File, DB, Seq, Elastic)
  • Better performance & flexibility
Step 1: Install Packages
dotnet add package Serilog.AspNetCore
dotnet add package Serilog.Sinks.Console
dotnet add package Serilog.Sinks.File

Step 2: Configure Serilog in Program.cs
using Serilog;

Log.Logger = new LoggerConfiguration()
    .Enrich.FromLogContext()
    .WriteTo.Console()
    .WriteTo.File("Logs/app-.log", rollingInterval: RollingInterval.Day)
    .CreateLogger();

builder.Host.UseSerilog();

Step 3: Use ILogger as Usual.
_logger.LogInformation("Invoice {InvoiceId} generated", invoiceId);
You still use ILoggerSerilog works behind the scenes.

Interview Answer: In ASP.NET Core, I use ILogger for application logging and Serilog for structured, production-grade logging. I follow proper log levels, structured messages, correlation IDs, and centralized log storage to ensure observability and easy debugging.
0

No comments

Post a Comment

both, mystorymag

DON'T MISS

Tech News
© all rights reserved
made with by AlgoLesson
Table of Contents