您现在的位置是:网站首页> 编程资料编程资料
使用NLog给Asp.Net Core做请求监控的方法_实用技巧_
2023-05-24
337人已围观
简介 使用NLog给Asp.Net Core做请求监控的方法_实用技巧_
为了减少由于单个请求挂掉而拖垮整站的情况发生,给所有请求做统计是一个不错的解决方法,通过观察哪些请求的耗时比较长,我们就可以找到对应的接口、代码、数据表,做有针对性的优化可以提高效率。在 asp.net web api 中我们可以通过注册一个 DelegatingHandler 来实现该功能。那在 asp.net core 中该如何实现呢?
一:比较 asp.net web api 和 asp.net core 的请求管道

观察这两张图,可以发现他们非常的相似,都是管道式的设计,在 asp.net web api 中,我们可以注册一系列的 DelegatingHandler 来处理请求上下文 HttpRequestMessage,在 asp.net core 中,我们可以注册一系列中间件来处理请求上下文,他们两者从功能和意义上是非常相似的,我这里这里不会详细介绍各自的管道是如何的(这样的文章非常多,博客园随处可见),他们都完成了类似中间件的功能,只是在代码设计上有一点区别。
我们先看一段代码,新建一个 asp.net web api 项目,添加几个 DelegatinHandler
然后在 Global 中注册
public class DelegatingHandler1 : DelegatingHandler { protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { Trace.WriteLine("DelegatingHandler1 HashCode: " + this.GetHashCode()); Trace.WriteLine("DelegatingHandler1 base InnerHandler HashCode: " + base.InnerHandler.GetHashCode()); Trace.WriteLine("DelegatingHandler1 start"); var response = await base.SendAsync(request, cancellationToken); Trace.WriteLine("DelegatingHandler1 end"); return response; } } public class DelegatingHandler2 : DelegatingHandler { protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { Trace.WriteLine("DelegatingHandler2 HashCode: " + this.GetHashCode()); Trace.WriteLine("DelegatingHandler2 base InnerHandler HashCode: " + base.InnerHandler.GetHashCode()); Trace.WriteLine("DelegatingHandler2 start"); var response = await base.SendAsync(request, cancellationToken); Trace.WriteLine("DelegatingHandler2 end"); return response; } } public class DelegatingHandler3 : DelegatingHandler { protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { Trace.WriteLine("DelegatingHandler3 HashCode: " + this.GetHashCode()); Trace.WriteLine("DelegatingHandler3 base InnerHandler HashCode: " + base.InnerHandler.GetHashCode()); Trace.WriteLine("DelegatingHandler3 start"); var response = await base.SendAsync(request, cancellationToken); Trace.WriteLine("DelegatingHandler3 end"); return response; } } 修改一下 ValuesController
public class WebApiApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); GlobalConfiguration.Configuration.MessageHandlers.Add(new DelegatingHandler1()); GlobalConfiguration.Configuration.MessageHandlers.Add(new DelegatingHandler2()); GlobalConfiguration.Configuration.MessageHandlers.Add(new DelegatingHandler3()); } }启动后输入路径 /api/values,我们可以在VS 的输出栏看到下面这些内容
public class ValuesController : ApiController { // GET api/values public IEnumerable Get() { Trace.WriteLine("/api/values"); var handlers = this.RequestContext.Configuration.MessageHandlers; return new string[] { "value1", "value2" }; } } 启动后输入路径 /api/values,我们可以在VS 的输出栏看到下面这些内容
DelegatingHandler1 HashCode: 58154627
DelegatingHandler1 base InnerHandler HashCode: 35529478
DelegatingHandler1 start
DelegatingHandler2 HashCode: 35529478
DelegatingHandler2 base InnerHandler HashCode: 47422476
DelegatingHandler2 start
DelegatingHandler3 HashCode: 47422476
DelegatingHandler3 base InnerHandler HashCode: 65273341
DelegatingHandler3 start
/api/values
DelegatingHandler3 end
DelegatingHandler2 end
DelegatingHandler1 end
输出中我们可以看到 DelegatingHandler1 的 InnerHandler 是 DelegatingHandler2,以此类推,在 DelegatingHandler3 的 InnerHandler 处理请求的时候就转发到了相关控制器,这里和 .net core 中的中间件非常相似,在.net core 中间件顺序是 RequestServicesContainerMiddleware(给请求上下文绑定容器)-> AuthenticationMiddleware(认证)-> RouterMiddleware (路由以及MVC)
如果我们在 ValuesController 中观察表达式 this.RequestContext.Configuration.MessageHandlers 还可以看到最终处理请求的是一个 HttpRoutingDispatcher,最也是是分配到路由以及控制器来处理的,按照如此方式我们可以很容易在 asp.net web api 中对请求统计。这里是比较简陋的,对此我们可以记录客户端和服务器更详细的信息,包括 IP 地址,http状态码,是否是认证用户等等,但是这篇主要是以 asp.net core 为主的,所以这里就不详细写下去了。
public class ApplicationInsight : DelegatingHandler { protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var stopWatch = new Stopwatch(); stopWatch.Start(); var response = await base.SendAsync(request, cancellationToken); stopWatch.Stop(); //停止计时器,并记录 } } public partial class Startup { public void Configuration(IAppBuilder app) { GlobalConfiguration.Configuration.MessageHandlers.Add(new ApplicationInsight()); } } 二:asp.net core 中间件 + NLog 实现请求监控
先看统计结果,start 开始时间,time 是请求消耗时间(毫秒),authenicate 是认证通过的 schema,使用 NLog 自定义字段也是非常方便的

先说一说遇到的问题
(1)NLog 记录一张以上的表如何实现,应为首先会有一个一般性的日志表(称他为 log),并且这些统计不对写到 log 表
(2)使用 NLog 自定义字段 LayoutRenderer 没有类似 .net framework 中的 System.Web.Current
(3)使用 UseMiddleware 无法在让我们的中间件成为第一个中间件
(4)实现忽略记录的方法,肯定有一些接口是不希望记录的,所以这个也要实现
NLog 配置
这里只列出了部分内容,github 地址在最后,数据库是 mysql ,apiinsight 表示请求统计,log 是一般性的日志,debughelper 可以加快我们调试时日志的检索速度
在 Startup 中
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { //省略了其他配置 //全局的 HttpContext app.UseGlobalHttpContext(); //省略了其他配置 LogManager.Configuration = new XmlLoggingConfiguration(Path.Combine(env.ContentRootPath, "nlog.config")); LogManager.Configuration.Variables["root"] = env.ContentRootPath; LogManager.Configuration.Variables["connectionString"] = Configuration.GetConnectionString("DefaultConnection"); }自定义字段都是通过 LayoutRenderer 实现,由于自定义字段有很多,这里只列出了一个开始时间是如何查询的,这个时间是在我们注册的第一个中间件执行 Invoke 方法的时候写进 HttpContext.Items 的
[LayoutRenderer("apiinsight-start")] public class StartApiInsightRenderer : LayoutRenderer { protected override void Append(StringBuilder builder, LogEventInfo logEvent) { var httpContext = HttpContextProvider.Current; if (httpContext == null) { return; } var _apiInsightsKeys = httpContext.RequestServices.GetService(); if (httpContext != null) { if (httpContext.Items.TryGetValue(_apiInsightsKeys.StartTimeName, out var start) == true) { builder.Append(start.ToString()); } } } } NLog 规则,很容易理解日志统计只记录 Cheers 命名空间下的日志
核心 ApiInsightMiddleware 中间件
public class ApiInsightMiddleware { private readonly RequestDelegate _next; private readonly IServiceProvider _serverProvider; private readonly IApiInsightsKeys _apiInsightsKeys; private readonly ILogger _logger; private HttpContext _httpContext; public ApiInsightMiddleware(RequestDelegate next, IServiceProvider serviceProvider, ILogger logger) { _next = next; _serverProvider = serviceProvider; _apiInsightsKeys = _serverProvider.GetService(); _logger = logger; } public async Task Invoke(HttpContext httpContext) { _httpContext = httpContext; var flag = SetValues(); await _next(httpContext); if (flag == true) { ApiInsight(); } } //省略了其他的代码 } 很好理解,在执行下一个中间件之前调用 SetValues 开始计时,下一个中间件执行成功开始统计并写入日志(或者忽略不写)。现在他是 asp.net core mvc 的第一个中间件了,好处就是更符合这个中间件本身的所做的事情了,但是带来的问题就是 httpContext.RequestService 是 null ,因为 RequestService 是在 RequestServicesContainerMiddleware 这个中间件写进去的,在者其实很多地方我们都需要 HttpContext ,并且目前微软还没有给我们定义一个静态的 HttpContext。
静态的 HttpContext
HttpContext 是通过单例 IHttpContextAccessor 提供的,当 HttpContext 创建的时候就会赋值给他,当请求到达中间件这个管道的时候,HttpContext 就已经存在于 IHttpContextAccessor 了,并且和 Invoke 参数列表中的 HttpContext 是一致的(同一个请求中),问题在于 RequestServicesContainerMiddleware 这个中间件没有执行就没有容器,并且很多时候我们都要用到容器,所以就模仿源码在这里都加进去了。
public static class HttpContextProvider { private static IHttpContextAccessor _accessor; private static IServiceScopeFactory _serviceScopeFactory; public static Microsoft.AspNetCore.Http.HttpContext Current { get { var context = _accessor?.HttpContext; if (context != null) { var replacementFeature = new RequestServicesFeature(_serviceScop
相关内容
点击排行
本栏推荐
