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

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 的日志

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

Memo

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

大型应用可以用比较专业的 APM 工具,最近比较火的 [Skywalking](https://github.com/
apache/skywalking) 项目可以了解一下,支持 .NET Core, 详细信息参考: https://github.com/SkyAPM/SkyAPM-dotnet

Reference