LogAttribute .cs 2.6 KB

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