LogAttribute .cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. string res = "在返回结果前发生了异常";
  33. if (context.Result == null)
  34. {
  35. res = "无返回结果";
  36. }
  37. else
  38. {
  39. dynamic result = context.Result.GetType().Name == "EmptyResult" ? new { Value = "无返回结果" } : context.Result as dynamic;
  40. try
  41. {
  42. if (result != null)
  43. {
  44. res = Newtonsoft.Json.JsonConvert.SerializeObject(result.Value);
  45. }
  46. }
  47. catch (Exception)
  48. {
  49. res = "日志未获取到结果,返回的数据无法序列化";
  50. }
  51. }
  52. var msg = $"方法:{LogFlag}-地址:{url}-方式:{method}-耗时:{Stopwatch.Elapsed.TotalMilliseconds}毫秒(指控制器内对应方法执行完毕的时间)\n" +
  53. $"参数:{qs}\n " +
  54. $"结果:{res}";
  55. LogHub.InterfacePublish(LogFlag, msg);
  56. }
  57. }
  58. }