Created
December 23, 2025 08:09
-
-
Save MirzaLeka/43a776e7d0bcc684f7089bbee9189404 to your computer and use it in GitHub Desktop.
Custom logger in global exception handler
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | |
| ); | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| services.AddSingleton(typeof(IAppLogger<>), typeof(AppLogger<>)); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | |
| }; | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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