【问题标题】:Log method execution time with .NET annotation [duplicate]使用.NET注释记录方法执行时间[重复]
【发布时间】:2018-12-04 11:48:54
【问题描述】:

是否有任何现有的库可以仅使用方法注释来记录方法执行时间(我更喜欢 serilog、anotar.serilog)?

【问题讨论】:

标签: c# .net serilog


【解决方案1】:

如果您的意图是记录控制器/操作的经过时间。您可以为此编写自己的中间件。检查以下示例:

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>();
}

【讨论】:

  • 没有提到实际使用 ASP.NET 的 OP。如发布的那样,您可以在 ASP.NET 中记录控制器调用的执行时间,它不能记录任意方法的执行时间。
  • 相应地编辑了我的帖子
猜你喜欢
  • 2021-07-12
  • 2011-04-09
  • 1970-01-01
  • 1970-01-01
  • 2020-04-22
  • 2015-08-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多