AuditingInterceptor.cs 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. using System;
  2. using System.Diagnostics;
  3. using System.Threading.Tasks;
  4. using Abp.Aspects;
  5. using Abp.Threading;
  6. using Castle.DynamicProxy;
  7. namespace Abp.Auditing
  8. {
  9. internal class AuditingInterceptor : IInterceptor
  10. {
  11. private readonly IAuditingHelper _auditingHelper;
  12. public AuditingInterceptor(IAuditingHelper auditingHelper)
  13. {
  14. _auditingHelper = auditingHelper;
  15. }
  16. public void Intercept(IInvocation invocation)
  17. {
  18. if (AbpCrossCuttingConcerns.IsApplied(invocation.InvocationTarget, AbpCrossCuttingConcerns.Auditing))
  19. {
  20. invocation.Proceed();
  21. return;
  22. }
  23. if (!_auditingHelper.ShouldSaveAudit(invocation.MethodInvocationTarget))
  24. {
  25. invocation.Proceed();
  26. return;
  27. }
  28. var auditInfo = _auditingHelper.CreateAuditInfo(invocation.TargetType, invocation.MethodInvocationTarget, invocation.Arguments);
  29. if (invocation.Method.IsAsync())
  30. {
  31. PerformAsyncAuditing(invocation, auditInfo);
  32. }
  33. else
  34. {
  35. PerformSyncAuditing(invocation, auditInfo);
  36. }
  37. }
  38. private void PerformSyncAuditing(IInvocation invocation, AuditInfo auditInfo)
  39. {
  40. var stopwatch = Stopwatch.StartNew();
  41. try
  42. {
  43. invocation.Proceed();
  44. }
  45. catch (Exception ex)
  46. {
  47. auditInfo.Exception = ex;
  48. throw;
  49. }
  50. finally
  51. {
  52. stopwatch.Stop();
  53. auditInfo.ExecutionDuration = Convert.ToInt32(stopwatch.Elapsed.TotalMilliseconds);
  54. _auditingHelper.Save(auditInfo);
  55. }
  56. }
  57. private void PerformAsyncAuditing(IInvocation invocation, AuditInfo auditInfo)
  58. {
  59. var stopwatch = Stopwatch.StartNew();
  60. invocation.Proceed();
  61. if (invocation.Method.ReturnType == typeof(Task))
  62. {
  63. invocation.ReturnValue = InternalAsyncHelper.AwaitTaskWithFinally(
  64. (Task) invocation.ReturnValue,
  65. exception => SaveAuditInfo(auditInfo, stopwatch, exception)
  66. );
  67. }
  68. else //Task<TResult>
  69. {
  70. invocation.ReturnValue = InternalAsyncHelper.CallAwaitTaskWithFinallyAndGetResult(
  71. invocation.Method.ReturnType.GenericTypeArguments[0],
  72. invocation.ReturnValue,
  73. exception => SaveAuditInfo(auditInfo, stopwatch, exception)
  74. );
  75. }
  76. }
  77. private void SaveAuditInfo(AuditInfo auditInfo, Stopwatch stopwatch, Exception exception)
  78. {
  79. stopwatch.Stop();
  80. auditInfo.Exception = exception;
  81. auditInfo.ExecutionDuration = Convert.ToInt32(stopwatch.Elapsed.TotalMilliseconds);
  82. _auditingHelper.Save(auditInfo);
  83. }
  84. }
  85. }