LogHandler.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using System;
  2. using System.Diagnostics;
  3. using System.Linq;
  4. using System.Threading.Tasks;
  5. using Microsoft.AspNetCore.Mvc;
  6. using Microsoft.AspNetCore.Mvc.Filters;
  7. using Microsoft.Extensions.Logging;
  8. using ZhonTai.Common.Output;
  9. using ZhonTai.Plate.Admin.Service.OprationLog;
  10. using ZhonTai.Plate.Admin.Service.OprationLog.Input;
  11. //using Newtonsoft.Json;
  12. namespace ZhonTai.Plate.Admin.HttpApi.Shared.Logs
  13. {
  14. /// <summary>
  15. /// 操作日志处理
  16. /// </summary>
  17. public class LogHandler : ILogHandler
  18. {
  19. private readonly ILogger _logger;
  20. private readonly ApiHelper _apiHelper;
  21. private readonly IOprationLogService _oprationLogService;
  22. public LogHandler(
  23. ILogger<LogHandler> logger,
  24. ApiHelper apiHelper,
  25. IOprationLogService oprationLogService
  26. )
  27. {
  28. _logger = logger;
  29. _apiHelper = apiHelper;
  30. _oprationLogService = oprationLogService;
  31. }
  32. public async Task LogAsync(ActionExecutingContext context, ActionExecutionDelegate next)
  33. {
  34. var sw = new Stopwatch();
  35. sw.Start();
  36. var actionExecutedContext = await next();
  37. sw.Stop();
  38. //操作参数
  39. //var args = JsonConvert.SerializeObject(context.ActionArguments);
  40. //操作结果
  41. //var result = JsonConvert.SerializeObject(actionResult?.Value);
  42. try
  43. {
  44. var input = new OprationLogAddInput
  45. {
  46. ApiMethod = context.HttpContext.Request.Method.ToLower(),
  47. ApiPath = context.ActionDescriptor.AttributeRouteInfo.Template.ToLower(),
  48. ElapsedMilliseconds = sw.ElapsedMilliseconds
  49. };
  50. if (actionExecutedContext.Result is ObjectResult result && result.Value is IResponseOutput res)
  51. {
  52. input.Status = res.Success;
  53. input.Msg = res.Msg;
  54. }
  55. input.ApiLabel = _apiHelper.GetApis().FirstOrDefault(a => a.Path == input.ApiPath)?.Label;
  56. await _oprationLogService.AddAsync(input);
  57. }
  58. catch (Exception ex)
  59. {
  60. _logger.LogError("操作日志插入异常:{@ex}", ex);
  61. }
  62. }
  63. }
  64. }