在上面两篇介绍了ABP中的ValidationInterceptor之后,我们今天来看看ABP中定义的另外一种Interceptor即为AuditingInterceptor,顾名思义就是一种审计相关的作用,在了解这篇文章之前,你也可以先看一下ABP官方文档,从而对这个过程有一个更清晰的理解,整个过程也是从AbpBootstrapper中的AddInterceptorRegistrars方法开始的,在这个方法中首先对AuditingInterceptor进行初始化操作,具体的来看看下面的代码。

  1. internal static class AuditingInterceptorRegistrar
  2. {
  3. public static void Initialize(IIocManager iocManager)
  4. {
  5. iocManager.IocContainer.Kernel.ComponentRegistered += (key, handler) =>
  6. {
  7. if (!iocManager.IsRegistered<IAuditingConfiguration>())
  8. {
  9. return;
  10. }
  11.  
  12. var auditingConfiguration = iocManager.Resolve<IAuditingConfiguration>();
  13.  
  14. if (ShouldIntercept(auditingConfiguration, handler.ComponentModel.Implementation))
  15. {
  16. handler.ComponentModel.Interceptors.Add(new InterceptorReference(typeof(AuditingInterceptor)));
  17. }
  18. };
  19. }
  20.  
  21. private static bool ShouldIntercept(IAuditingConfiguration auditingConfiguration, Type type)
  22. {
  23. if (auditingConfiguration.Selectors.Any(selector => selector.Predicate(type)))
  24. {
  25. return true;
  26. }
  27.  
  28. if (type.GetTypeInfo().IsDefined(typeof(AuditedAttribute), true))
  29. {
  30. return true;
  31. }
  32.  
  33. if (type.GetMethods().Any(m => m.IsDefined(typeof(AuditedAttribute), true)))
  34. {
  35. return true;
  36. }
  37.  
  38. return false;
  39. }
  40. }

  在这个方法内部,首先将整个ABP中唯一的IoCManager作为参数传递到里面,然后订阅依赖注入容器的ComponentRegister事件,这里订阅的函数有两个参数,一个是key,另外一个是IHandle的接口,这段代码意思是说当Ioc中有组件被注册的时候(也就是往Ioc添加某个类型的时候), 就会触发ComponentRegister事件,然后执行事件的订阅操作,在这个订阅事件处理中首先判断当前的ABP中是否注册过IAuditingConfiguration这个接口,如果没有注册过那么就直接返回了,如果对前面的文章有过印象的话,你就知道这个注册的过程是沿着下面的过程来进行的:UseAbp--》InitializeAbp(app)--》abpBootstrapper.Initialize()--》IocManager.IocContainer.Install(new AbpCoreInstaller());在最后执行AbpCoreInstaller的时候,在这个类中有一个Install方法,在这个里面就对ABP中常用的接口都注册并注入到容器中了。

  1. internal class AbpCoreInstaller : IWindsorInstaller
  2. {
  3. public void Install(IWindsorContainer container, IConfigurationStore store)
  4. {
  5. container.Register(
  6. Component.For<IUnitOfWorkDefaultOptions, UnitOfWorkDefaultOptions>().ImplementedBy<UnitOfWorkDefaultOptions>().LifestyleSingleton(),
  7. Component.For<INavigationConfiguration, NavigationConfiguration>().ImplementedBy<NavigationConfiguration>().LifestyleSingleton(),
  8. Component.For<ILocalizationConfiguration, LocalizationConfiguration>().ImplementedBy<LocalizationConfiguration>().LifestyleSingleton(),
  9. Component.For<IAuthorizationConfiguration, AuthorizationConfiguration>().ImplementedBy<AuthorizationConfiguration>().LifestyleSingleton(),
  10. Component.For<IValidationConfiguration, ValidationConfiguration>().ImplementedBy<ValidationConfiguration>().LifestyleSingleton(),
  11. Component.For<IFeatureConfiguration, FeatureConfiguration>().ImplementedBy<FeatureConfiguration>().LifestyleSingleton(),
  12. Component.For<ISettingsConfiguration, SettingsConfiguration>().ImplementedBy<SettingsConfiguration>().LifestyleSingleton(),
  13. Component.For<IModuleConfigurations, ModuleConfigurations>().ImplementedBy<ModuleConfigurations>().LifestyleSingleton(),
  14. Component.For<IEventBusConfiguration, EventBusConfiguration>().ImplementedBy<EventBusConfiguration>().LifestyleSingleton(),
  15. Component.For<IMultiTenancyConfig, MultiTenancyConfig>().ImplementedBy<MultiTenancyConfig>().LifestyleSingleton(),
  16. Component.For<ICachingConfiguration, CachingConfiguration>().ImplementedBy<CachingConfiguration>().LifestyleSingleton(),
  17. Component.For<IAuditingConfiguration, AuditingConfiguration>().ImplementedBy<AuditingConfiguration>().LifestyleSingleton(),
  18. Component.For<IBackgroundJobConfiguration, BackgroundJobConfiguration>().ImplementedBy<BackgroundJobConfiguration>().LifestyleSingleton(),
  19. Component.For<INotificationConfiguration, NotificationConfiguration>().ImplementedBy<NotificationConfiguration>().LifestyleSingleton(),
  20. Component.For<IEmbeddedResourcesConfiguration, EmbeddedResourcesConfiguration>().ImplementedBy<EmbeddedResourcesConfiguration>().LifestyleSingleton(),
  21. Component.For<IAbpStartupConfiguration, AbpStartupConfiguration>().ImplementedBy<AbpStartupConfiguration>().LifestyleSingleton(),
  22. Component.For<IEntityHistoryConfiguration, EntityHistoryConfiguration>().ImplementedBy<EntityHistoryConfiguration>().LifestyleSingleton(),
  23. Component.For<ITypeFinder, TypeFinder>().ImplementedBy<TypeFinder>().LifestyleSingleton(),
  24. Component.For<IAbpPlugInManager, AbpPlugInManager>().ImplementedBy<AbpPlugInManager>().LifestyleSingleton(),
  25. Component.For<IAbpModuleManager, AbpModuleManager>().ImplementedBy<AbpModuleManager>().LifestyleSingleton(),
  26. Component.For<IAssemblyFinder, AbpAssemblyFinder>().ImplementedBy<AbpAssemblyFinder>().LifestyleSingleton(),
  27. Component.For<ILocalizationManager, LocalizationManager>().ImplementedBy<LocalizationManager>().LifestyleSingleton()
  28. );
  29. }
  30. }

  有了上面的分析,你大概知道了这个继承自IAuditingConfiguration接口的AuditingConfiguration会作为唯一的实例注入到ABP中的容器内部。在这之后会执行一个非常重要的函数ShouldIntercept,这个方法用来判断哪些形式的能够最终执行当前的Interceptor,在这个方法中,后面两种都比较好理解,如果一个类比如说继承自IApplicationService的一个应用服务类在其顶部或者内部的方法中添加了AuditAttribute自定义CustomerAttribute,那么就会执行审计过程,如果是定义在类的级别中那么该类中的所有请求的方法都会执行后面的审计AuditingInterceptor,如果不是定义在类级别上,而是定义在类里面的方法中,那么只有请求了该方法的时候才会执行当前审计操作。这里面不太好理解的就是第一种判断方式。在ABP中默认添加了一个Selector,这个实在AbpKenelModule的PreInitialize()中添加的。

  1. private void AddAuditingSelectors()
  2. {
  3. Configuration.Auditing.Selectors.Add(
  4. new NamedTypeSelector(
  5. "Abp.ApplicationServices",
  6. type => typeof(IApplicationService).IsAssignableFrom(type)
  7. )
  8. );
  9. }

  这个也是比较好理解的,就是所有从IApplicationService继承的类都会默认添加AuditingInterceptor,另外我们在我们自己的项目中的PreInitialize()方法中自定义规则,这个是ABP中对外扩展的一种方式。在了解完这些后你应该完全了解ABP中默认对哪些类型进行AuditingInterceptor拦截了。

  接下来的重点就是去分析 AuditingInterceptor这个Interceptor这个具体的拦截器到底是怎样工作的。

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

  在这个里面,当我们将要被执行Auditing方法之前,首先会执行AuditingInterceptor 类中的Intercept方法,在这个方法体内部,首先也是执行AbpCrossCuttingConcerns.IsApplied方法,在这个方法中首先会判断这个执行当前方法所属的类是否是从IAvoidDuplicateCrossCuttingConcerns接口继承,如果从这个接口继承的话,那么将执行方法的所属的类转换为IAvoidDuplicateCrossCuttingConcerns类型,然后再看当前接口中定义的List<string>类型的AppliedCrossCuttingConcerns对象中是否已经包含AbpAuditing字符串,如果已经包含那么就直接执行拦截的方法,然后就返回。这里需要特别注意的是在整个ABP系统中只有一个ApplicationService继承自IAvoidDuplicateCrossCuttingConcerns这个接口,所以在我们的系统中,只有继承自ApplicationService类的类中的方法被拦截器拦截时才会执行上面的过程。这个分析过程其实和之前的ValidationInterceptor中的分析过程是一致的,所以这里就不再赘述,直接拿出结果。

  ABP中利用Asp.Net Core中的过滤器的特性其实也定义了一组Filter,这个可以看下面的代码。在Asp.Net Core中执行ConfigureServices的时候会执行AddAbp方法在这个方法中会执行对MvcOptions的一些操作。

  1. //Configure MVC
  2. services.Configure<MvcOptions>(mvcOptions =>
  3. {
  4. mvcOptions.AddAbp(services);
  5. });

  我们来看看这个mvcOptions的AddAbp方法。

  1. internal static class AbpMvcOptionsExtensions
  2. {
  3. public static void AddAbp(this MvcOptions options, IServiceCollection services)
  4. {
  5. AddConventions(options, services);
  6. AddFilters(options);
  7. AddModelBinders(options);
  8. }
  9.  
  10. private static void AddConventions(MvcOptions options, IServiceCollection services)
  11. {
  12. options.Conventions.Add(new AbpAppServiceConvention(services));
  13. }
  14.  
  15. private static void AddFilters(MvcOptions options)
  16. {
  17. options.Filters.AddService(typeof(AbpAuthorizationFilter));
  18. options.Filters.AddService(typeof(AbpAuditActionFilter));
  19. options.Filters.AddService(typeof(AbpValidationActionFilter));
  20. options.Filters.AddService(typeof(AbpUowActionFilter));
  21. options.Filters.AddService(typeof(AbpExceptionFilter));
  22. options.Filters.AddService(typeof(AbpResultFilter));
  23. }
  24.  
  25. private static void AddModelBinders(MvcOptions options)
  26. {
  27. options.ModelBinderProviders.Insert(0, new AbpDateTimeModelBinderProvider());
  28. }
  29. }

  在这个方法中,ABP系统默认添加了6中类型的Filter,这其中就包括AbpAuditActionFilter,在这个Filter中,我们来看看到底做了些什么?

  1. public class AbpAuditActionFilter : IAsyncActionFilter, ITransientDependency
  2. {
  3. private readonly IAbpAspNetCoreConfiguration _configuration;
  4. private readonly IAuditingHelper _auditingHelper;
  5.  
  6. public AbpAuditActionFilter(IAbpAspNetCoreConfiguration configuration, IAuditingHelper auditingHelper)
  7. {
  8. _configuration = configuration;
  9. _auditingHelper = auditingHelper;
  10. }
  11.  
  12. public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
  13. {
  14. if (!ShouldSaveAudit(context))
  15. {
  16. await next();
  17. return;
  18. }
  19.  
  20. using (AbpCrossCuttingConcerns.Applying(context.Controller, AbpCrossCuttingConcerns.Auditing))
  21. {
  22. var auditInfo = _auditingHelper.CreateAuditInfo(
  23. context.ActionDescriptor.AsControllerActionDescriptor().ControllerTypeInfo.AsType(),
  24. context.ActionDescriptor.AsControllerActionDescriptor().MethodInfo,
  25. context.ActionArguments
  26. );
  27.  
  28. var stopwatch = Stopwatch.StartNew();
  29.  
  30. try
  31. {
  32. var result = await next();
  33. if (result.Exception != null && !result.ExceptionHandled)
  34. {
  35. auditInfo.Exception = result.Exception;
  36. }
  37. }
  38. catch (Exception ex)
  39. {
  40. auditInfo.Exception = ex;
  41. throw;
  42. }
  43. finally
  44. {
  45. stopwatch.Stop();
  46. auditInfo.ExecutionDuration = Convert.ToInt32(stopwatch.Elapsed.TotalMilliseconds);
  47. await _auditingHelper.SaveAsync(auditInfo);
  48. }
  49. }
  50. }
  51.  
  52. private bool ShouldSaveAudit(ActionExecutingContext actionContext)
  53. {
  54. return _configuration.IsAuditingEnabled &&
  55. actionContext.ActionDescriptor.IsControllerAction() &&
  56. _auditingHelper.ShouldSaveAudit(actionContext.ActionDescriptor.GetMethodInfo(), true);
  57. }
  58. }

  在继承自ApplicationService的类中的方法执行之前,首先会执行OnActionExecutionAsync方法,在这个方法中首先判断一些基础的条件,这些通常都是一些默认的设置,在判断完这些类型以后,就会执行下面的这些方法,在这个方法中会将默认的字符串AbpAuditing

  名称 类型
(obj as IAvoidDuplicateCrossCuttingConcerns) {Castle.Proxies.SelfAppServiceroxy} Abp.Application.Services.IAvoidDuplicateCrossCuttingConcerns {Castle.Proxies.SelfAppServiceProxy}

写入到一个默认的List<string>类型中,这个具体过程可以参考上面的分析,在AbpCrossCuttingConcerns.Applying中第一个参数最为关键,那么这个context.Controller(也就是上图中obj对应的参数)到底指的是什么呢?这里我们执行一个继承自ApplicationService中的SelfAppService中的一个方法时,我们通过调试发现最终的类型是Castle.Proxies.SelfAppServiceProxy 类型,如果对这个还不太理解,可以这么理解其实就是我们自定义的SelfAppService这个继承自ApplicationService 类的类型。

  再在后面就是通过构造函数注入的IAuditingHelper对象来创建一个auditInfo,这个创建的类是最关键的,ABP系统中有一个默认的IAuditingHelper的实现,我们来重点看看这个类中到底做了些什么?

  1. public class AuditingHelper : IAuditingHelper, ITransientDependency
  2. {
  3. public ILogger Logger { get; set; }
  4. public IAbpSession AbpSession { get; set; }
  5. public IAuditingStore AuditingStore { get; set; }
  6.  
  7. private readonly IAuditInfoProvider _auditInfoProvider;
  8. private readonly IAuditingConfiguration _configuration;
  9. private readonly IUnitOfWorkManager _unitOfWorkManager;
  10. private readonly IAuditSerializer _auditSerializer;
  11.  
  12. public AuditingHelper(
  13. IAuditInfoProvider auditInfoProvider,
  14. IAuditingConfiguration configuration,
  15. IUnitOfWorkManager unitOfWorkManager,
  16. IAuditSerializer auditSerializer)
  17. {
  18. _auditInfoProvider = auditInfoProvider;
  19. _configuration = configuration;
  20. _unitOfWorkManager = unitOfWorkManager;
  21. _auditSerializer = auditSerializer;
  22.  
  23. AbpSession = NullAbpSession.Instance;
  24. Logger = NullLogger.Instance;
  25. AuditingStore = SimpleLogAuditingStore.Instance;
  26. }
  27.  
  28. public bool ShouldSaveAudit(MethodInfo methodInfo, bool defaultValue = false)
  29. {
  30. if (!_configuration.IsEnabled)
  31. {
  32. return false;
  33. }
  34.  
  35. if (!_configuration.IsEnabledForAnonymousUsers && (AbpSession?.UserId == null))
  36. {
  37. return false;
  38. }
  39.  
  40. if (methodInfo == null)
  41. {
  42. return false;
  43. }
  44.  
  45. if (!methodInfo.IsPublic)
  46. {
  47. return false;
  48. }
  49.  
  50. if (methodInfo.IsDefined(typeof(AuditedAttribute), true))
  51. {
  52. return true;
  53. }
  54.  
  55. if (methodInfo.IsDefined(typeof(DisableAuditingAttribute), true))
  56. {
  57. return false;
  58. }
  59.  
  60. var classType = methodInfo.DeclaringType;
  61. if (classType != null)
  62. {
  63. if (classType.GetTypeInfo().IsDefined(typeof(AuditedAttribute), true))
  64. {
  65. return true;
  66. }
  67.  
  68. if (classType.GetTypeInfo().IsDefined(typeof(DisableAuditingAttribute), true))
  69. {
  70. return false;
  71. }
  72.  
  73. if (_configuration.Selectors.Any(selector => selector.Predicate(classType)))
  74. {
  75. return true;
  76. }
  77. }
  78.  
  79. return defaultValue;
  80. }
  81.  
  82. public AuditInfo CreateAuditInfo(Type type, MethodInfo method, object[] arguments)
  83. {
  84. return CreateAuditInfo(type, method, CreateArgumentsDictionary(method, arguments));
  85. }
  86.  
  87. public AuditInfo CreateAuditInfo(Type type, MethodInfo method, IDictionary<string, object> arguments)
  88. {
  89. var auditInfo = new AuditInfo
  90. {
  91. TenantId = AbpSession.TenantId,
  92. UserId = AbpSession.UserId,
  93. ImpersonatorUserId = AbpSession.ImpersonatorUserId,
  94. ImpersonatorTenantId = AbpSession.ImpersonatorTenantId,
  95. ServiceName = type != null
  96. ? type.FullName
  97. : "",
  98. MethodName = method.Name,
  99. Parameters = ConvertArgumentsToJson(arguments),
  100. ExecutionTime = Clock.Now
  101. };
  102.  
  103. try
  104. {
  105. _auditInfoProvider.Fill(auditInfo);
  106. }
  107. catch (Exception ex)
  108. {
  109. Logger.Warn(ex.ToString(), ex);
  110. }
  111.  
  112. return auditInfo;
  113. }
  114.  
  115. public void Save(AuditInfo auditInfo)
  116. {
  117. using (var uow = _unitOfWorkManager.Begin(TransactionScopeOption.Suppress))
  118. {
  119. AuditingStore.Save(auditInfo);
  120. uow.Complete();
  121. }
  122. }
  123.  
  124. public async Task SaveAsync(AuditInfo auditInfo)
  125. {
  126. using (var uow = _unitOfWorkManager.Begin(TransactionScopeOption.Suppress))
  127. {
  128. await AuditingStore.SaveAsync(auditInfo);
  129. await uow.CompleteAsync();
  130. }
  131. }
  132.  
  133. private string ConvertArgumentsToJson(IDictionary<string, object> arguments)
  134. {
  135. try
  136. {
  137. if (arguments.IsNullOrEmpty())
  138. {
  139. return "{}";
  140. }
  141.  
  142. var dictionary = new Dictionary<string, object>();
  143.  
  144. foreach (var argument in arguments)
  145. {
  146. if (argument.Value != null && _configuration.IgnoredTypes.Any(t => t.IsInstanceOfType(argument.Value)))
  147. {
  148. dictionary[argument.Key] = null;
  149. }
  150. else
  151. {
  152. dictionary[argument.Key] = argument.Value;
  153. }
  154. }
  155.  
  156. return _auditSerializer.Serialize(dictionary);
  157. }
  158. catch (Exception ex)
  159. {
  160. Logger.Warn(ex.ToString(), ex);
  161. return "{}";
  162. }
  163. }
  164.  
  165. private static Dictionary<string, object> CreateArgumentsDictionary(MethodInfo method, object[] arguments)
  166. {
  167. var parameters = method.GetParameters();
  168. var dictionary = new Dictionary<string, object>();
  169.  
  170. for (var i = 0; i < parameters.Length; i++)
  171. {
  172. dictionary[parameters[i].Name] = arguments[i];
  173. }
  174.  
  175. return dictionary;
  176. }
  177. }

  在这个类中重点的就是CreateAuditInfo这个方法,这个方法会创建一个AuditInfo对象,然后往这个对象中填充一些系统的常见的一些信息,比如:TenantId、UserId、ServiceName等等一系类的常用对象,我们来看看AuditInfo这个对象包含哪些重要的东西吧?

  1. public class AuditInfo
  2. {
  3. /// <summary>
  4. /// TenantId.
  5. /// </summary>
  6. public int? TenantId { get; set; }
  7.  
  8. /// <summary>
  9. /// UserId.
  10. /// </summary>
  11. public long? UserId { get; set; }
  12.  
  13. /// <summary>
  14. /// ImpersonatorUserId.
  15. /// </summary>
  16. public long? ImpersonatorUserId { get; set; }
  17.  
  18. /// <summary>
  19. /// ImpersonatorTenantId.
  20. /// </summary>
  21. public int? ImpersonatorTenantId { get; set; }
  22.  
  23. /// <summary>
  24. /// Service (class/interface) name.
  25. /// </summary>
  26. public string ServiceName { get; set; }
  27.  
  28. /// <summary>
  29. /// Executed method name.
  30. /// </summary>
  31. public string MethodName { get; set; }
  32.  
  33. /// <summary>
  34. /// Calling parameters.
  35. /// </summary>
  36. public string Parameters { get; set; }
  37.  
  38. /// <summary>
  39. /// Start time of the method execution.
  40. /// </summary>
  41. public DateTime ExecutionTime { get; set; }
  42.  
  43. /// <summary>
  44. /// Total duration of the method call.
  45. /// </summary>
  46. public int ExecutionDuration { get; set; }
  47.  
  48. /// <summary>
  49. /// IP address of the client.
  50. /// </summary>
  51. public string ClientIpAddress { get; set; }
  52.  
  53. /// <summary>
  54. /// Name (generally computer name) of the client.
  55. /// </summary>
  56. public string ClientName { get; set; }
  57.  
  58. /// <summary>
  59. /// Browser information if this method is called in a web request.
  60. /// </summary>
  61. public string BrowserInfo { get; set; }
  62.  
  63. /// <summary>
  64. /// Optional custom data that can be filled and used.
  65. /// </summary>
  66. public string CustomData { get; set; }
  67.  
  68. /// <summary>
  69. /// Exception object, if an exception occurred during execution of the method.
  70. /// </summary>
  71. public Exception Exception { get; set; }
  72.  
  73. public override string ToString()
  74. {
  75. var loggedUserId = UserId.HasValue
  76. ? "user " + UserId.Value
  77. : "an anonymous user";
  78.  
  79. var exceptionOrSuccessMessage = Exception != null
  80. ? "exception: " + Exception.Message
  81. : "succeed";
  82.  
  83. return $"AUDIT LOG: {ServiceName}.{MethodName} is executed by {loggedUserId} in {ExecutionDuration} ms from {ClientIpAddress} IP address with {exceptionOrSuccessMessage}.";
  84. }
  85. }

  在创建完这个用来保存AuditingInfo的AuditInfo对象后,接下来的事情就比较明了了,就是创建一个StopWatch用于记录当前方法执行的时间,后面再用一个try、catch、finally来包装执行的方法,捕获错误,并将当前的Exception捕获并赋值给刚才创建的auditInfo中,完成这个步骤之后就是将整个AuditInfo进行保存从而方便我们对当前方法进行排错和优化效率的操作了。

  在执行完最重要的步骤之后就是如何保存这些重要的信息了,我们来一起看看这个重要的步骤都做了些什么吧?

  1. public async Task SaveAsync(AuditInfo auditInfo)
  2. {
  3. using (var uow = _unitOfWorkManager.Begin(TransactionScopeOption.Suppress))
  4. {
  5. await AuditingStore.SaveAsync(auditInfo);
  6. await uow.CompleteAsync();
  7. }
  8. }

  在这个函数里面,执行一个AuditingStore的SaveAsync的方法,这是一个异步方法,用来对最终的信息进行保存。ABP中默认是采用日志的方式来将当前的auditInfo转化为字符串然后保存到日志文件中的,当然我们也可以将当前的信息保存到数据库中的,这样我们就能够查看更多的系统运行状态的信息了,下面是一张具体的截图我们来看看。

  最后,点击这里返回整个ABP系列的主目录。

ABP中的拦截器之AuditingInterceptor的更多相关文章

  1. ABP中的拦截器之ValidationInterceptor(上)

    从今天这一节起就要深入到ABP中的每一个重要的知识点来一步步进行分析,在进行介绍ABP中的拦截器之前我们先要有个概念,到底什么是拦截器,在介绍这些之前,我们必须要了解AOP编程思想,这个一般翻译是面向 ...

  2. ABP中的拦截器之EntityHistoryInterceptor

    今天我们接着之前的系列接着来写另外一种拦截器EntityHistoryInterceptor,这个拦截器到底是做什么的呢?这个从字面上理解是实体历史?这个到底是什么意思?带着这个问题我们来一步步去分析 ...

  3. ABP中的拦截器之ValidationInterceptor(下)

    在上篇我分析了整个ABP中ValitationInterceptor的整个过程,就其中涉及到的Validator过程没有详细的论述,这篇文章就这个过程进行详细的论述,另外任何一个重要的特性如何应用是最 ...

  4. 6. abp中的拦截器

    abp拦截器基本定义 拦截器接口定义: public interface IAbpInterceptor { void Intercept(IAbpMethodInvocation invocatio ...

  5. ABP拦截器之UnitOfWorkRegistrar(一)

    ABP中UnitOfWorkRegistrar拦截器是整个ABP中非常关键的一个部分,这个部分在整个业务系统中也是用的最多的一个部分,这篇文章的主要思路并不是写如何使用ABP中的UnitOfWork, ...

  6. ABP拦截器之AuthorizationInterceptor

    在整体介绍这个部分之前,如果对ABP中的权限控制还没有一个很明确的认知,请先阅读这篇文章,然后在读下面的内容. AuthorizationInterceptor看这个名字我们就知道这个拦截器拦截用户一 ...

  7. ABP拦截器之UnitOfWorkRegistrar(二)

    在上面一篇中我们主要是了解了在ABP系统中是如何使用UnitOfWork以及整个ABP系统中如何执行这些过程的,那么这一篇就让我们来看看UnitOfWorkManager中在执行Begin和Compl ...

  8. ABP中的Filter(上)

    这个部分我打算用上下两个部分来将整个结构来讲完,在我们读ABP中的代码之后我们一直有一个疑问?在ABP中为什么要定义Interceptor和Filter,甚至这两者之间我们都能找到一些对应关系,比如: ...

  9. ABP源码分析三十五:ABP中动态WebAPI原理解析

    动态WebAPI应该算是ABP中最Magic的功能之一了吧.开发人员无须定义继承自ApiController的类,只须重用Application Service中的类就可以对外提供WebAPI的功能, ...

随机推荐

  1. PhpStudy升级MySQL5.7

    PhpStudy2017集成环境中的mysql数据库的版本默认是mysql5.5,下面是PhpStudy升级数据库到mysql5.7的方法: 1:备份当前数据库数据,可以导出数据库文件,作为备份,我这 ...

  2. 字符串hash入门

    简单介绍一下字符串hash 相信大家对于hash都不陌生 翻译过来就是搞砸,乱搞的意思嘛 hash算法广泛应用于计算机的各类领域,像什么md5,文件效验,磁力链接 等等都会用到hash算法 在信息学奥 ...

  3. Mysql基本操作指令集锦

    一.MySQL服务的启动.停止与卸载 在 Windows 命令提示符下运行: 启动: net start MySQL 停止: net stop MySQL 卸载: sc delete MySQL 二. ...

  4. CentOS 7安装指南

    CentOS 7安装指南(U盘版) 一.准备阶段 1.下载CentOS7镜像文件(ISO文件)到自己电脑,官网下载路径: http://isoredirect.centos.org/centos/7/ ...

  5. 我想要革命想要解脱——bootstrap常见问题及解决方式

    最近一个月,恍若隔世,天天加班,昨晚终于发版了,今天才喘一口气.有时候,即便你工作效率再怎么高,撸码再怎么快也无可避免的会加班.不信的话,可以先给你定一个交付时间,然后不断的给你加需求,就让你一个人做 ...

  6. BGP:所有邻居都启动了BGP,则无须建立首尾逻辑邻居,否则就需要首尾建立逻辑邻居。

    配置说明:都通过loopback 口作为bgp 连接口,并且要配置ebgp多跳,同时配置loopback口的静态路由. 以AR2为例: 第一种场景:所有直接相连的邻居都启动了BGP,则路由可以随意扩散 ...

  7. 仿9GAG制作过程(二)

    有话要说: 这次准备讲述用python爬虫以及将爬来的数据存到MySQL数据库的过程,爬的是煎蛋网的无聊图. 成果: 准备: 下载了python3.7并配置好了环境变量 下载了PyCharm作为开发p ...

  8. Spark读Hbase优化 --手动划分region提高并行数

    一. Hbase的region 我们先简单介绍下Hbase的架构和Hbase的region: 从物理集群的角度看,Hbase集群中,由一个Hmaster管理多个HRegionServer,其中每个HR ...

  9. c/c++ llinux epoll系列4 利用epoll_wait实现非阻塞的connect

    llinux epoll系列4 利用epoll_wait实现非阻塞的connect connect函数是阻塞的,而且不能设置connect函数的timeout时间,所以一旦阻塞太长时间,影响用户的体验 ...

  10. errno 的使用

    error是一个包含在<errno.h>中的预定义的外部int变量,用于表示最近一个函数调用是否产生了错误.若为0,则无错误,其它值均表示一类错误. perror()和strerror() ...