88
99namespace Commmunity . AspNetCore . ExceptionHandling . Logs
1010{
11- public class LogExceptionHandler < TException > : IExceptionHandler
11+ public class LogExceptionHandler < TException > : HandlerStrongType < TException >
1212 where TException : Exception
1313 {
1414 private readonly IOptions < LogHandlerOptions < TException > > _settings ;
@@ -17,11 +17,12 @@ public class LogExceptionHandler<TException> : IExceptionHandler
1717
1818 public LogHandlerOptions < TException > Settings => this . _settings . Value ;
1919
20- public LogExceptionHandler ( IOptions < LogHandlerOptions < TException > > settings )
20+ public LogExceptionHandler ( IOptions < LogHandlerOptions < TException > > settings , ILoggerFactory loggerFactory ) : base ( settings . Value , loggerFactory )
2121 {
2222 _settings = settings ?? throw new ArgumentNullException ( nameof ( settings ) ) ;
2323 }
24- public Task < HandlerResult > Handle ( HttpContext httpContext , Exception exception )
24+
25+ protected override Task < HandlerResult > HandleStrongType ( HttpContext httpContext , TException exception )
2526 {
2627 var logLevel = this . Settings . Level ? . Invoke ( httpContext , exception ) ?? LogLevel . Error ;
2728
@@ -43,17 +44,26 @@ public Task<HandlerResult> Handle(HttpContext httpContext, Exception exception)
4344
4445 EventId eventId = this . Settings . EventIdFactory != null
4546 ? this . Settings . EventIdFactory ( httpContext , exception )
46- : DefaultEvent ;
47+ : DefaultEvent ;
4748
4849 object state = this . Settings . StateFactory ? . Invoke ( httpContext , exception , this . Settings ) ??
4950 new FormattedLogValues ( "Unhandled error occured. RequestId: {requestId}." ,
5051 httpContext . TraceIdentifier ) ;
5152
52- Func < object , Exception , string > formatter = this . Settings . Formatter ?? ( ( o , e ) => o . ToString ( ) ) ;
53+ Func < object , Exception , string > formatter ;
5354
54- logger . Log ( logLevel , eventId , state , exception , formatter ) ;
55+ if ( this . Settings . Formatter != null )
56+ {
57+ formatter = ( o , e ) => this . Settings . Formatter ( 0 , e as TException ) ;
58+ }
59+ else
60+ {
61+ formatter = ( o , e ) => o . ToString ( ) ;
62+ }
63+
64+ logger . Log ( logLevel , eventId , state , exception , formatter ) ;
5565 }
56-
66+
5767 return Task . FromResult ( HandlerResult . NextHandler ) ;
5868 }
5969 }
0 commit comments