1- using System . Linq ;
1+ using System ;
2+ using System . Linq ;
23using System . Diagnostics ;
34using System . Threading . Tasks ;
5+ using Microsoft . AspNetCore . Mvc ;
6+ using Microsoft . AspNetCore . Mvc . Filters ;
7+ using Microsoft . Extensions . Logging ;
48using Admin . Core . Common . Output ;
59using Admin . Core . Service . Admin . OprationLog ;
610using Admin . Core . Service . Admin . OprationLog . Input ;
7- using Microsoft . AspNetCore . Mvc . Filters ;
811//using Newtonsoft.Json;
912
1013namespace Admin . Core . Logs
@@ -14,14 +17,17 @@ namespace Admin.Core.Logs
1417 /// </summary>
1518 public class LogHandler : ILogHandler
1619 {
20+ private readonly ILogger _logger ;
1721 private readonly ApiHelper _apiHelper ;
1822 private readonly IOprationLogService _oprationLogService ;
1923
2024 public LogHandler (
25+ ILogger < LogHandler > logger ,
2126 ApiHelper apiHelper ,
2227 IOprationLogService oprationLogService
2328 )
2429 {
30+ _logger = logger ;
2531 _apiHelper = apiHelper ;
2632 _oprationLogService = oprationLogService ;
2733 }
@@ -30,27 +36,37 @@ public async Task LogAsync(ActionExecutingContext context, ActionExecutionDelega
3036 {
3137 var sw = new Stopwatch ( ) ;
3238 sw . Start ( ) ;
33- dynamic actionResult = ( await next ( ) ) . Result ;
39+ var actionExecutedContext = await next ( ) ;
3440 sw . Stop ( ) ;
3541
3642 //操作参数
3743 //var args = JsonConvert.SerializeObject(context.ActionArguments);
3844 //操作结果
3945 //var result = JsonConvert.SerializeObject(actionResult?.Value);
4046
41- var res = actionResult ? . Value as IResponseOutput ;
42-
43- var input = new OprationLogAddInput
47+ try
4448 {
45- ApiMethod = context . HttpContext . Request . Method . ToLower ( ) ,
46- ApiPath = context . ActionDescriptor . AttributeRouteInfo . Template . ToLower ( ) ,
47- ElapsedMilliseconds = sw . ElapsedMilliseconds ,
48- Status = res ? . Success ,
49- Msg = res ? . Msg
50- } ;
51- input . ApiLabel = _apiHelper . GetApis ( ) . FirstOrDefault ( a => a . Path == input . ApiPath ) ? . Label ;
49+ var input = new OprationLogAddInput
50+ {
51+ ApiMethod = context . HttpContext . Request . Method . ToLower ( ) ,
52+ ApiPath = context . ActionDescriptor . AttributeRouteInfo . Template . ToLower ( ) ,
53+ ElapsedMilliseconds = sw . ElapsedMilliseconds
54+ } ;
5255
53- await _oprationLogService . AddAsync ( input ) ;
56+ if ( actionExecutedContext . Result is ObjectResult result && result . Value is IResponseOutput res )
57+ {
58+ input . Status = res . Success ;
59+ input . Msg = res . Msg ;
60+ }
61+
62+ input . ApiLabel = _apiHelper . GetApis ( ) . FirstOrDefault ( a => a . Path == input . ApiPath ) ? . Label ;
63+
64+ await _oprationLogService . AddAsync ( input ) ;
65+ }
66+ catch ( Exception ex )
67+ {
68+ _logger . LogError ( "操作日志插入异常:{@ex}" , ex ) ;
69+ }
5470 }
5571 }
5672}
0 commit comments