net5 Http請求整體處理耗時
阿新 • • 發佈:2022-03-04
net5 webapi http請求處理耗時統計
問題:如何記錄http處理耗時
通過中介軟體記錄耗時
app.UseMiddleware<TestMiddleware>();
app.UseRouting();
app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
Stopwatch sw = Stopwatch.StartNew(); _logger.LogInformation("1"); var date = DateTime.Now; await next(context); _logger.LogInformation($"{date:yyyy-MM-dd HH:mm:ss fff}----{swElapsedMilliseconds}");
Filter記錄
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { Stopwatch sw = Stopwatch.StartNew(); context.HttpContext.Items.Add("Stopwatch", sw); var loggerFactory = context.HttpContext.RequestServices.GetService<ILoggerFactory>(); var logger = loggerFactory.CreateLogger("123"); logger.LogInformation("3"); await next(); logger.LogInformation("4"); } public async Task OnResultExecutionAsync(ResultExecutingContext context, ResultExecutionDelegate next) { var loggerFactory = context.HttpContext.RequestServices.GetService<ILoggerFactory>(); var logger = loggerFactory.CreateLogger("123"); logger.LogInformation("5"); await next(); var sw = context.HttpContext.Items["Stopwatch"] as Stopwatch; logger.LogInformation($"6----耗時{sw.ElapsedMilliseconds}"); }
Action記錄
[HttpGet] [CustomerLogFilter] public async Task<string> Get() { _logger.LogInformation("2"); Stopwatch sw = Stopwatch.StartNew(); var enterTime = DateTime.Now; var time = enterTime.ToUniversalTime()-new DateTime(1970,1,1,0,0,0,0); var preCount = ThreadPool.ThreadCount; var tempCount = Interlocked.Increment(ref _count); await Task.Delay(200); var executeCount = ThreadPool.ThreadCount; var timess = time.TotalMilliseconds*10000; _logger.LogInformation($"2----耗時:{sw.ElapsedMilliseconds}"); return $"----{timess}----{sw.ElapsedMilliseconds}----{tempCount}----{preCount}----{executeCount}----{enterTime:yyyy-MM-dd HH:mm:ss.fff}"; }
結果
2022-03-04 15:55:54.778 +08:00 [INF] 1
2022-03-04 15:55:54.942 +08:00 [INF] 3
2022-03-04 15:55:54.952 +08:00 [INF] 2
2022-03-04 15:55:55.161 +08:00 [INF] 2----耗時:207
2022-03-04 15:55:55.185 +08:00 [INF] 4
2022-03-04 15:55:55.189 +08:00 [INF] 5
2022-03-04 15:55:55.205 +08:00 [INF] 6----耗時264
2022-03-04 15:55:55.207 +08:00 [INF] 2022-03-04 15:55:54 837----432