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

2022-10-16,,,,

intro

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

中间件实现

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<iloggerfactory>()
     .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 的日志

memo

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

大型应用可以用比较专业的 apm 工具,最近比较火的 skywalking 项目可以了解一下,支持 .net core, 详细信息参考: https://github.com/skyapm/skyapm-dotnet

reference

https://github.com/weihanli/activityreservation

总结

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

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

下载本文的Word格式文档,以方便收藏与打印。