LogHandler.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. using System.Linq;
  2. using System.Diagnostics;
  3. using System.Threading.Tasks;
  4. using Admin.Core.Model.Output;
  5. using Admin.Core.Service.Admin.OprationLog;
  6. using Admin.Core.Service.Admin.OprationLog.Input;
  7. using Microsoft.AspNetCore.Mvc.Filters;
  8. using Newtonsoft.Json;
  9. using Newtonsoft.Json.Linq;
  10. namespace Admin.Core.Logs
  11. {
  12. /// <summary>
  13. /// 操作日志处理
  14. /// </summary>
  15. public class LogHandler : ILogHandler
  16. {
  17. private readonly ApiHelper _apiHelper;
  18. private readonly IOprationLogService _oprationLogService;
  19. public LogHandler(
  20. ApiHelper apiHelper,
  21. IOprationLogService oprationLogService
  22. )
  23. {
  24. _apiHelper = apiHelper;
  25. _oprationLogService = oprationLogService;
  26. }
  27. public async Task LogAsync(ActionExecutingContext context, ActionExecutionDelegate next)
  28. {
  29. var sw = new Stopwatch();
  30. sw.Start();
  31. dynamic actionResult = (await next()).Result;
  32. sw.Stop();
  33. //操作参数
  34. //var args = JsonConvert.SerializeObject(context.ActionArguments);
  35. //操作结果
  36. //var result = JsonConvert.SerializeObject(actionResult?.Value);
  37. var res = actionResult?.Value as IResponseOutput;
  38. var input = new OprationLogAddInput
  39. {
  40. ApiMethod = context.HttpContext.Request.Method.ToLower(),
  41. ApiPath = context.ActionDescriptor.AttributeRouteInfo.Template.ToLower(),
  42. ElapsedMilliseconds = sw.ElapsedMilliseconds,
  43. Status = res?.Success,
  44. Msg = res?.Msg
  45. };
  46. input.ApiLabel = _apiHelper.GetApis().FirstOrDefault(a => a.Path == input.ApiPath)?.Label;
  47. await _oprationLogService.AddAsync(input);
  48. }
  49. }
  50. }