LogAttribute .cs 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. base.OnActionExecuting(context);
  22. // 后续添加了获取请求的请求体,如果在实际项目中不需要删除即可
  23. long contentLen = context.HttpContext.Request.ContentLength == null ? 0 : context.HttpContext.Request.ContentLength.Value;
  24. if (contentLen > 0)
  25. {
  26. // 读取请求体中所有内容
  27. Stream stream = context.HttpContext.Request.Body;
  28. if (context.HttpContext.Request.Method == "POST")
  29. {
  30. stream.Position = 0;
  31. }
  32. byte[] buffer = new byte[contentLen];
  33. stream.Read(buffer, 0, buffer.Length);
  34. // 转化为字符串
  35. RequestBody = System.Text.Encoding.UTF8.GetString(buffer);
  36. }
  37. ActionArguments = Newtonsoft.Json.JsonConvert.SerializeObject(context.ActionArguments);
  38. Stopwatch = new Stopwatch();
  39. Stopwatch.Start();
  40. }
  41. public override void OnActionExecuted(ActionExecutedContext context)
  42. {
  43. base.OnActionExecuted(context);
  44. Stopwatch.Stop();
  45. string url = context.HttpContext.Request.Host + context.HttpContext.Request.Path + context.HttpContext.Request.QueryString;
  46. string method = context.HttpContext.Request.Method;
  47. string qs = ActionArguments;
  48. dynamic result = context.Result.GetType().Name == "EmptyResult" ? new { Value = "无返回结果" } : context.Result as dynamic;
  49. string res = "在返回结果前发生了异常";
  50. try
  51. {
  52. if (result != null)
  53. {
  54. res = Newtonsoft.Json.JsonConvert.SerializeObject(result.Value);
  55. }
  56. }
  57. catch (Exception)
  58. {
  59. res = "日志未获取到结果,返回的数据无法序列化";
  60. }
  61. var msg = $"\n 方法:{LogFlag} \n " +
  62. $"地址:{url} \n " +
  63. $"方式:{method} \n " +
  64. $"请求体:{RequestBody} \n " +
  65. $"参数:{qs}\n " +
  66. $"结果:{res}\n " +
  67. $"耗时:{Stopwatch.Elapsed.TotalMilliseconds} 毫秒(指控制器内对应方法执行完毕的时间)";
  68. LogHub.InterfacePublish("测试", msg);
  69. }
  70. }
  71. }