# Error Handling & Logging with Serilog in ASP.NET Core

You can’t fix what you can’t see. That’s why **error handling** and **structured logging** are critical in production ASP.NET Core apps.

In this article, we’ll integrate **Serilog**, handle errors globally, and capture logs like a pro.

---

## 🔧 Why Serilog?

Serilog is a diagnostic logging library that makes logs:
- 🔍 Searchable
- 📊 Structured (JSON, key-value pairs)
- 🔌 Pluggable (to file, console, Seq, Application Insights, etc.)

---

## 📦 Step 1: Install Serilog Packages

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

Optional:
```bash
dotnet add package Serilog.Sinks.Console
dotnet add package Serilog.Sinks.Seq
```

---

## 🛠️ Step 2: Configure Serilog in Program.cs

```csharp
using Serilog;

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

var builder = WebApplication.CreateBuilder(args);
builder.Host.UseSerilog();

var app = builder.Build();
```

Now all logs are automatically captured.

---

## ⚠️ Step 3: Global Error Handling

Create a middleware:

```csharp
public class ErrorHandlerMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger<ErrorHandlerMiddleware> _logger;

    public ErrorHandlerMiddleware(RequestDelegate next, ILogger<ErrorHandlerMiddleware> logger)
    {
        _next = next;
        _logger = logger;
    }

    public async Task Invoke(HttpContext context)
    {
        try
        {
            await _next(context);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Unhandled error occurred.");
            context.Response.StatusCode = 500;
            await context.Response.WriteAsJsonAsync(new { error = "An unexpected error occurred." });
        }
    }
}
```

Register it in `Program.cs` before other middleware:

```csharp
app.UseMiddleware<ErrorHandlerMiddleware>();
```

---

## 🧪 Where Logs Go

By default:
- Console → for local development
- `Logs/log.txt` → daily rotating files

Optional: send logs to:
- 📊 Seq (real-time log dashboard)
- ☁️ Azure Application Insights
- 📤 ElasticSearch

---

## 🧠 Best Practices

- ✅ Log structured data (`@object`) instead of raw strings
- ✅ Avoid logging sensitive data (passwords, tokens)
- ✅ Use log levels appropriately: `Information`, `Warning`, `Error`, `Fatal`, `Debug`

---

## ✅ Up Next

Your app can now self-report errors. Next, we’ll learn how to build **Minimal APIs** for fast, focused endpoints without full controller setup.

➡️ [Minimal APIs: Fast, Lean, and Powerful →](./minimal-api-guide)

Let’s keep your code clean and your logs even cleaner 💡

