写接口的不免会遇到别人说接口比较慢,到底慢多少,一个接口服务器处理究竟花了多长时间,若是能有具体的数字来记录每一个接口耗时多少,别人再说接口慢的时候看一下接口耗时统计,若是几毫秒就处理完了,对不起这锅我不背。html
asp.net core 的运行是一个又一个的中间件来完成的,所以咱们只须要定义本身的中间件,记录请求开始处理前的时间和处理结束后的时间,这里的中间件把请求的耗时输出到日志里了,你也能够根据须要输出到响应头或其余地方。git
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
里配置请求处理管道,示例配置以下:github
app.UsePerformanceLog(); app.UseAuthentication(); app.UseMvc(routes => { // ... }); // ...
在日志里按 Logger 名称 “PerformanceLog” 搜索日志,日志里的 ElapsedMilliseconds
就是对应接口的耗时时间,也能够按 ElapsedMilliseconds
范围来搜索,好比筛选耗时时间大于 1s 的日志apache
这个中间件比较简单,只是一个处理思路。api
大型应用能够用比较专业的 APM 工具,最近比较火的 [Skywalking](https://github.com/ apache/skywalking) 项目能够了解一下,支持 .NET Core, 详细信息参考: https://github.com/SkyAPM/SkyAPM-dotnet服务器
原文出处:https://www.cnblogs.com/weihanli/p/record-aspnetcore-api-elapsed-milliseconds-via-custom-middleware.htmlapp