LogHandler.cs 2.1 KB

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