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.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
var builder = WebApplication.CreateBuilder(args);
// Configure logging
builder.Logging.ClearProviders();
builder.Logging.AddConsole();
builder.Logging.AddFile("Logs/app-{Date}.log");
var app = builder.Build();
// Add custom middleware for exception logging
app.UseMiddleware<ExceptionLoggingMiddleware>();
// Define endpoints
app.MapGet("/", () => "Hello World!");
app.Run();
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
}
}
} 4. Set Up File Permissions for IIS
- Create a Logs directory in your application root
- Right-click the Logs folder in Windows Explorer.
- Go to Properties.
- Navigate to the Security tab.
- Click Edit, then Add, and enter IIS_IUSRS.
- Grant Write permissions to the IIS_IUSRS user.
Comments
Post a Comment