Skip to main content

Posts

Showing posts from May, 2024

ASP.NET Core - Log exceptions to the IIS log

This is only applicable when you are NOT using MVC in your application 1. Required Packages :  Microsoft.Extensions.Logging Microsoft.Extensions.Logging.Console 2. Middleware for Exception Login :  public class ExceptionLoggingMiddleware { private readonly RequestDelegate _next; private readonly ILogger<ExceptionLoggingMiddleware> _logger; public ExceptionLoggingMiddleware(RequestDelegate next, ILogger<ExceptionLoggingMiddleware> logger) { _next = next; _logger = logger; } public async Task InvokeAsync(HttpContext context) { try { await _next(context); } catch (Exception ex) { _logger.LogError(ex, "An unhandled exception occurred."); throw; // Rethrow the exception after logging it } } } 3. Configure your Program.cs using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInject...