日志操作,如何实现更好

Logging operations, how to implement better

我需要使用许多日志记录信息(时间等)实现一些方法调用的日志记录。我可以这样做:

var stopwatch = new Stopwatch();
OCRResult ocrResult = await ocr.GetTextAsync(dataStream, filename, language);
stopwatch.Stop();
// log here, with time, result etc

它会起作用,但我不喜欢这种方法。首先,我在很多地方都有很多这样的调用,我不得不复制代码。其次,这种方法违反了 SRP(单一责任原则),即每次调用只做一项工作。我需要做一个包装器或使用策略模式,无论如何我应该再创建一个 class 来完成它。但是如何实现呢?

您可以创建一个通用方法来测量函数的时间并记录它:

public static void LogFunc<T>(Func<T> func)
{
    var stopwatch = Stopwatch.StartNew();
    T result = func();
    stopwatch.Stop();
    long time = stopwatch.ElapsedMilliseconds;
    // log here, with time, result etc
}

LogFunc(async () => await ocr.GetTextAsync(dataStream, filename, language));

此方法的 async 版本:

public static async Task LogFuncAsync<T>(Func<Task<T>> func)
{
    var stopwatch = Stopwatch.StartNew();
    T result = await func();
    stopwatch.Stop();
    long time = stopwatch.ElapsedMilliseconds;
    // log here, with time, result etc
}

await LogFuncAsync(() => ocr.GetTextAsync(dataStream, filename, language));

关注 "Kfir Guy" 的回答 我修改了他的回答并得到以下内容:

    public static async Task LogFuncAsync<T>(Func<Task<T>> func)
    {
        var stopwatch = Stopwatch.StartNew();
        T result = await func();
        stopwatch.Stop();
        long time = stopwatch.ElapsedMilliseconds;
        // log here, with time, result etc
    }

并称它为:

await Utils.LogFuncAsync(async () => ocrResult = await ocr.GetTextAsync(dataStream, filename, language));