MethodPerformance.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. using AspectCore.DynamicProxy;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using XYY.Core.Standard;
  8. using XYY.Core.Standard.Data.Infrastructure;
  9. namespace XYY.PerformanceCount.Standard
  10. {
  11. public class MethodPerformanceAttrice : AbstractInterceptorAttribute
  12. {
  13. private string _methodName;
  14. public MethodPerformanceAttrice(string MethodName)
  15. {
  16. this._methodName = MethodName;
  17. }
  18. public override async Task Invoke(AspectContext context, AspectDelegate next)
  19. {
  20. IPerformanceDB db = null;
  21. try
  22. {
  23. db = context.ServiceProvider.GetService(typeof(IPerformanceDB)) as IPerformanceDB;
  24. if (db == null)
  25. throw new Exception("当前实例未注册IPerformanceDB接口实现");
  26. }
  27. catch (Exception ex)
  28. {
  29. throw new Exception("当前实例未注册IPerformanceDB接口实现:" + ex.Message);
  30. }
  31. DateTime startTime = DateTime.Now;
  32. Stopwatch watch = new Stopwatch();
  33. watch.Start();
  34. string responseMessage = "OK";
  35. try
  36. {
  37. await next.Invoke(context);
  38. }
  39. catch (Exception ex)
  40. {
  41. responseMessage = ex.Message;
  42. throw ex;
  43. }
  44. finally
  45. {
  46. watch.Stop();
  47. }
  48. var methodPerformance = context.GetAttribute<MethodPerformanceAttrice>();
  49. MethodPerformanceModel menthodPerformance = new MethodPerformanceModel
  50. {
  51. StartTime = startTime,
  52. ExecutionTime = watch.ElapsedMilliseconds,
  53. MehtodName = this._methodName,
  54. RequestParameters = Newtonsoft.Json.JsonConvert.SerializeObject(context.Parameters),
  55. ResponseMessage = responseMessage,
  56. Id = Guid.NewGuid()
  57. };
  58. await db.AddLog(menthodPerformance);
  59. }
  60. }
  61. }