使用.NET注释记录方法的执行时间

时间:2018-12-04 11:48:54

标签: c# .net serilog

是否存在仅通过方法注释记录方法执行时间的库(我更喜欢serilog,notar。serilog)?

1 个答案:

答案 0 :(得分:0)

如果您打算记录控制器/操作的经过时间。为此,您可以编写自己的中间件。请查看以下示例:

public class DiagnosticsMiddleware 
{
    private readonly RequestDelegate _next;

    public DiagnosticsMiddleware(RequestDelegate next, IElasticClient esClient)
    {
        _next = next;
        _esClient = esClient;
    }

    public async Task Invoke(HttpContext context)
    { 
        Stopwatch sw = Stopwatch.StartNew();


        await _next(context);

        sw.Stop();
        var elapsedTime = sw.ElapsedTicks / (Stopwatch.Frequency / (1000L * 1000L));
        LogContext.PushProperty("ElapsedTime", elapsedTime);
    }

}

您可以像配置

public void Configure(IApplicationBuilder app)
{
    app.UseMiddleware<ContextEnricherMiddleware>();
}