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

Memo
這個中間件比較簡單,只是一個處理思路。
大型應用可以用比較專業的 APM 工具,最近比較火的 [Skywalking](https://github.com/
apache/skywalking) 項目可以了解一下,支持 .NET Core, 詳細信息參考: https://github.com/SkyAPM/SkyAPM-dotnet
