在http://www.52jiagou.com/article/212这篇文章中,我们已经在.net core 中使用了Nlog并将日志写到txt中,现在使用AspectCore统一拦截所有的错误,在Startup.cs中的ConfigureServices方法中,先添加拦截设置:
//Aop services.AddDynamicProxy(config => { config.Interceptors.AddTyped<ErrorLogHandler>(Predicates.ForNameSpace("MyCore.*")); //拦截所有MyCore及其子命名空间下面的接口或类 });
添加类:
namespace MyCore.Infrastructure.Aop { public class ErrorLogHandler: AbstractInterceptorAttribute { protected static ILogger Log = Ioc.GetService<ILogger>(); public async override Task Invoke(AspectContext context, AspectDelegate next) { try { await next(context); } catch (Exception ex) { var sbErrorMsg = new StringBuilder(); sbErrorMsg.AppendLine($"传参:{Json.ToJson(context.Parameters)}"); sbErrorMsg.AppendLine($"Source:{ex.Source}"); sbErrorMsg.AppendLine($"方法:{context.Implementation.ToString()},{context.ImplementationMethod.ToString()}"); sbErrorMsg.AppendLine(ex.ToString()); Log.Error(sbErrorMsg.ToString()); throw ex; } } } }