Skip to content

Instantly share code, notes, and snippets.

@MirzaLeka
Created December 23, 2025 08:09
Show Gist options
  • Select an option

  • Save MirzaLeka/43a776e7d0bcc684f7089bbee9189404 to your computer and use it in GitHub Desktop.

Select an option

Save MirzaLeka/43a776e7d0bcc684f7089bbee9189404 to your computer and use it in GitHub Desktop.
Custom logger in global exception handler
public class AppLogger<T> : IAppLogger<T> where T : class
{
private readonly ILogger<T> _logger;
public AppLogger(ILogger<T> logger)
{
_logger = logger;
}
public void LogHTTPError(Exception ex, HttpContext httpContext, string statusCode, string id)
{
_logger.LogError(ex, "{Path} {Method}, {id}, {statusCode}",
httpContext.Request.Path,
httpContext.Request.Method,
id,
statusCode
);
}
services.AddSingleton(typeof(IAppLogger<>), typeof(AppLogger<>));
public sealed class GlobalExceptionHandler(
IProblemDetailsService problemDetailsService,
IAppLogger<GlobalExceptionHandler> logger
) : IExceptionHandler
{
private readonly IAppLogger<GlobalExceptionHandler> _logger = logger;
public async ValueTask<bool> TryHandleAsync(HttpContext httpContext, Exception exception, CancellationToken cancellationToken)
{
int statusCode = GetStatusCode(exception);
_logger.LogHTTPError(exception, httpContext, statusCode.ToString(), "X-ID");
return false;
}
private int GetStatusCode(Exception exception)
{
return exception switch
{
ApplicationException => StatusCodes.Status400BadRequest,
_ => StatusCodes.Status500InternalServerError
};
}
}
public interface IAppLogger<in T> where T : class
{
void LogHTTPError(Exception ex, HttpContext httpContext, string statusCode, string id);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment