Mastering Logging in .NET Core Web API – With Hands-On Examples!

Mastering Logging in .NET Core Web API

📘 Mastering Logging in .NET Core Web API – With Hands-On Examples!

Logging is the backbone of every well-built application. It helps track issues, debug errors, and monitor performance effortlessly. Whether you’re a beginner or an experienced developer, a well-structured logging system can save hours of debugging time.

1️⃣ Setting Up Logging in .NET Core

📦 Step 1: Create a Project

dotnet new webapi -n LoggingDemo
cd LoggingDemo

🛠️ Step 2: Configure Logging in Program.cs

var builder = WebApplication.CreateBuilder(args);

builder.Logging.ClearProviders();   // Remove default logging
builder.Logging.AddConsole();       // Console logs
builder.Logging.AddDebug();         // Debug window logs

var app = builder.Build();

app.MapControllers();
app.Run();
✅ Logs will now appear in the terminal and Visual Studio output!

2️⃣ Implementing Logging in Controllers

✏️ Example: Injecting ILogger

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    private readonly ILogger<WeatherForecastController> _logger;

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

    [HttpGet]
    public IActionResult Get()
    {
        _logger.LogInformation("WeatherForecastController.Get() called");

        try
        {
            throw new Exception("Simulated exception!");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error occurred while fetching data!");
        }

        return Ok(new { Message = "Check logs for details." });
    }
}

🪵 Logging Levels

LevelDescription
LogTrace()Most detailed logs
LogDebug()Useful for local debugging
LogInformation()Normal app behavior
LogWarning()Potential issues
LogError()Exceptions and errors
LogCritical()System crash or critical failure

3️⃣ Configuring Logging in appsettings.json

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  }
}
📘 Explanation:
Default logs everything from Information upwards.
Microsoft filters out lower-level logs to avoid clutter.

4️⃣ Logging to File with Serilog

📦 Install Serilog Packages

dotnet add package Serilog.AspNetCore
dotnet add package Serilog.Sinks.File

🔧 Configure in Program.cs

using Serilog;

Log.Logger = new LoggerConfiguration()
    .WriteTo.Console()
    .WriteTo.File("logs/log.txt", rollingInterval: RollingInterval.Day)
    .CreateLogger();

builder.Host.UseSerilog();

5️⃣ Structured Logging with Serilog

_logger.LogInformation("User {UserId} logged in at {Time}", userId, DateTime.UtcNow);
🎯 Output (structured JSON):
{ "Message": "User 123 logged in at 2025-03-18T12:00:00Z" }
Structured logs help with filtering and searching in tools like Seq or ELK.

6️⃣ Centralized Logging with Seq

📦 Install Seq Sink

dotnet add package Serilog.Sinks.Seq

🔧 Configure Seq Sink in Program.cs

Log.Logger = new LoggerConfiguration()
    .WriteTo.Console()
    .WriteTo.Seq("http://localhost:5341")
    .CreateLogger();

🐳 Start Seq via Docker

docker run --name seq -d -p 5341:80 datalust/seq
📊 You can now monitor logs in a real-time dashboard using Seq!

🧠 Conclusion

  • ✅ Used ILogger<T> for built-in logging
  • ✅ Configured log levels via appsettings.json
  • ✅ Saved logs to files using Serilog
  • ✅ Used structured logging for searchability
  • ✅ Integrated Seq for centralized, real-time monitoring

Comments

Popular posts from this blog

Debouncing & Throttling in RxJS: Optimizing API Calls and User Interactions

Promises in Angular

Comprehensive Guide to C# and .NET Core OOP Concepts and Language Features