For Web API in .NET 6, I'm configuring Serilog
request logging.
app.UseSerilogRequestLogging(options =>
{
options.MessageTemplate = "Elapsed: {Elapsed:0.0000} ms";
});
How is Elapsed
calculated exactly?
CodePudding user response:
Serilog has custom RequestLoggingMiddleware
which is injected into pipeline via UseSerilogRequestLogging
call (that's why it is important to call this method as early as possible cause otherwise it will not take into account time consumed by components that appear before it in the pipeline, as mentioned in the docs). The implementation is pretty straightforward - sample time at the start of logging middleware, invoke the rest of pipeline, sample time at the end, calculate the difference. Currently calculation looks somewhat like this:
var start = Stopwatch.GetTimestamp();
var Elapsed = GetElapsedMilliseconds(start, Stopwatch.GetTimestamp());
static double GetElapsedMilliseconds(long start, long stop)
{
return (stop - start) * 1000 / (double)Stopwatch.Frequency;
}