我需要实现一些带有许多日志信息(时间等)的方法调用的日志记录。我可以这样做:
var stopwatch = new Stopwatch();
OCRResult ocrResult = await ocr.GetTextAsync(dataStream, filename, language);
stopwatch.Stop();
// log here, with time, result etc
它会起作用,但我不喜欢这种方法。首先,我在很多地方都有很多这样的调用,我必须对代码进行识别。其次,这种方法违反了SRP(单一责任原则),每次调用都可以完成一项工作。我需要做一个包装器或使用策略模式,无论如何我应该再创建一个类来完成它。但是如何实现呢?
答案 0 :(得分:2)
您可以创建一个测量函数时间并记录它的通用方法:
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));
答案 1 :(得分:0)
关注&#34; Kfir Guy&#34;回答我修改了他的答案,得到了以下内容:
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));