65.9K
CodeProject 正在变化。 阅读更多。
Home

捕获代码片段执行时间

starIconstarIconstarIconstarIconstarIcon

5.00/5 (1投票)

2024年10月8日

CPOL
viewsIcon

1965

downloadIcon

48

记录一段代码的执行时长,使用这个名为 SnippetDurationLogger 的 NuGet 包

下载 SnippetDurationLogger.zip

NuGet 包引用

引言

我相信,像我一样,在许多项目中你都不得不捕获和调查长时间运行的进程。你需要找到导致问题的代码片段,然后深入挖掘以查看哪些行导致了延迟。

你会在代码中散布大量的日志语句(而且经常会不小心把它们留下!!!)

背景

我创建的这个 NuGet 包,是为开发者希望捕获代码片段执行时间而开发的场景。不是整个方法的执行时间,而是在方法中的一段代码的执行时间,然后将其记录下来。

使用代码

将以下 NuGet 包添加到你的项目 - SnippetDurationLogger

将此命名空间添加到你的类

using SnippetDuration.Classes;

然后,围绕你希望获取执行时间的代码片段,应用 Logger 扩展方法 LogExecutionTime

_logger.LogExecutionTime("Add simple comment...", () =>
{
     // Your existing code block, whose execution time will be logged        
});

在你的注释中,你可以添加字符串插值变量:

_logger.LogExecutionTime($"Fnx parameter - {myParam}", () => 
{ 
      // Your existing code block, whose execution time will be logged 
});

然后在你的日志文件中,你将看到注释(如果包含插值值,则包含插值值)以及执行时间

下面是一个完整的示例

using Microsoft.Extensions.Logging;
using SnippetDuration.Classes;

namespace SnippetDurationLoggerConsole
{
    internal class ExternalMethods
    {
        private readonly ILogger<ExternalMethods> _logger;
        public ExternalMethods(ILogger<ExternalMethods> logger)
        {
            _logger = logger; // injected logger
        }

        public void LongRunningprocess()
        {
           _logger.LogExecutionTime("Testing DB Call", () =>              
            {
                // Code block whose execution time will be logged
                System.Threading.Thread.Sleep(3500); // Simulate a long running process
            });
        }
    }
}

 

© . All rights reserved.