To asp.net core middleware to write a time-consuming record interface
Intro
Write interfaces will inevitably encounter people say the interface is relatively slow, much slower in the end, an interface server handles exactly how long it took, if there are specific numbers to record the number of each interface time-consuming, others say it's time to see slower interfaces Interface statistics about the time-consuming, if a few milliseconds process is over, I'm sorry I can not back this pot.
Middleware
asp.net core is running one after another middleware to complete, so we only need to define their own middleware, the recording time after the request before the start of processing time and processing, middleware, where the time-consuming request output to the log, you can also output as needed to respond to the head or elsewhere.
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;
}
}
Middleware Configuration
In Startup
Lane configuration request processing pipeline, an exemplary configuration is as follows:
app.UsePerformanceLog();
app.UseAuthentication();
app.UseMvc(routes =>
{
// ...
});
// ...
Examples
In the log "PerformanceLog" search log, log by name Logger ElapsedMilliseconds
is time consuming correspondence interface, you can press ElapsedMilliseconds
to search, such as time-consuming screening log of time is greater than 1s
Memo
This middleware is relatively simple, just a thought process.
Large applications can use more professional APM tools, recent comparison of fire Skywalking project can find out, support for .NET Core, detailed reference information: https://github.com/SkyAPM/SkyAPM-dotnet