LogAttribute .cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. using Microsoft.AspNetCore.Mvc.Filters;
  2. using ServiceCenter.Logs;
  3. using System.Diagnostics;
  4. namespace ServiceCenter.Attributes
  5. {
  6. public class LogAttribute : ActionFilterAttribute
  7. {
  8. private string LogFlag { get; set; }
  9. private string ActionArguments { get; set; }
  10. /// <summary>
  11. /// 请求体中的所有值
  12. /// </summary>
  13. private string RequestBody { get; set; }
  14. private Stopwatch Stopwatch { get; set; }
  15. public LogAttribute(string logFlag)
  16. {
  17. LogFlag = logFlag;
  18. }
  19. public override void OnActionExecuting(ActionExecutingContext context)
  20. {
  21. ActionArguments = Newtonsoft.Json.JsonConvert.SerializeObject(context.ActionArguments);
  22. Stopwatch = new Stopwatch();
  23. Stopwatch.Start();
  24. }
  25. public override void OnActionExecuted(ActionExecutedContext context)
  26. {
  27. base.OnActionExecuted(context);
  28. Stopwatch.Stop();
  29. string url = context.HttpContext.Request.Host + context.HttpContext.Request.Path + context.HttpContext.Request.QueryString;
  30. string method = context.HttpContext.Request.Method;
  31. string qs = ActionArguments;
  32. dynamic result = context.Result.GetType().Name == "EmptyResult" ? new { Value = "无返回结果" } : context.Result as dynamic;
  33. string res = "在返回结果前发生了异常";
  34. try
  35. {
  36. if (result != null)
  37. {
  38. res = Newtonsoft.Json.JsonConvert.SerializeObject(result.Value);
  39. }
  40. }
  41. catch (Exception)
  42. {
  43. res = "日志未获取到结果,返回的数据无法序列化";
  44. }
  45. var msg = $"方法:{LogFlag}-地址:{url}-方式:{method}-耗时:{Stopwatch.Elapsed.TotalMilliseconds}毫秒(指控制器内对应方法执行完毕的时间)\n" +
  46. $"参数:{qs}\n " +
  47. $"结果:{res}";
  48. LogHub.InterfacePublish(LogFlag, msg);
  49. }
  50. }
  51. }