现在的位置: 首页 > 架构设计 > 正文

如何给asp.net core写个中间件记录接口耗时

2020年02月11日 架构设计 ⁄ 共 1293字 ⁄ 字号 评论关闭

  写接口的难免会遇到别人说接口比较慢,到底慢多少,一个接口服务器处理究竟花了多长时间,如果能有具体的数字来记录每个接口耗时多少,别人再说接口慢的时候看一下接口耗时统计,如果几毫秒就处理完了,对不起这锅我不背。

  中间件实现

  asp.net core 的运行是一个又一个的中间件来完成的,因此我们只需要定义自己的中间件,记录请求开始处理前的时间和处理结束后的时间,这里的中间件把请求的耗时输出到日志里了,你也可以根据需要输出到响应头或其他地方。

  public static class PerformanceLogExtension

  {

  public static IApplicationBuilder UsePerformanceLog(this IApplicationBuilder applicationBuilder)

  {

  applicationBuilder.Use(async (context, next) =>

  {

  var profiler = new StopwatchProfiler();

  profiler.Start();

  await next();

  profiler.Stop();

  var logger = context.RequestServices.GetService()

  .CreateLogger("PerformanceLog");

  logger.LogInformation("TraceId:{TraceId}, RequestMethod:{RequestMethod}, RequestPath:{RequestPath}, ElapsedMilliseconds:{ElapsedMilliseconds}, Response StatusCode: {StatusCode}",

  context.TraceIdentifier, context.Request.Method, context.Request.Path, profiler.ElapsedMilliseconds, context.Response.StatusCode);

  });

  return applicationBuilder;

  }

  }

  中间件配置

  在 Startup 里配置请求处理管道,示例配置如下:

  app.UsePerformanceLog();

  app.UseAuthentication();

  app.UseMvc(routes =>

  {

  // ...

  });

  // ...

  示例

  在日志里按 Logger 名称 “PerformanceLog” 搜索日志,日志里的 ElapsedMilliseconds 就是对应接口的耗时时间,也可以按 ElapsedMilliseconds 范围来搜索,比如筛选耗时时间大于 1s 的日志。

  这个中间件比较简单,只是一个处理思路。

  大型应用可以用比较专业的 APM 工具,最近比较火的 Skywalking 项目可以了解一下,支持 .NET Core。

  以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值。

抱歉!评论已关闭.