我需要在我的代码中进行一些日志记录。我需要使用公司内部开发的图书馆来记录一些信息。这是它的工作原理。
Recorder recorder = Recorder.StartTiming();
DoSomeWork();
recorder.Stop(); // Writes some diagnostic information.
为了确保 Stop() 总是被调用,我创建了一个允许干净的“使用”块的包装类。
using (RecorderWrapper recorderWrapper = new RecorderWrapper) // Automatically calls Recorder.StartTiming() under the covers
{
DoSomeWork();
} // When the recorderWrapper goes out of scope, the 'using' statement calls recorderWrapper.Dispose() automatically - which calls recorder.Stop() under the covers
到目前为止效果很好。但是,我的公司需要进行更改,在原始代码上看起来像这样:
Recorder recorder = Recorder.StartTiming();
try
{
DoSomeWork();
}
catch (Exception ex)
{
recorder.ReportFailure(ex); // Write out some exception details associated with this "transaction"
}
recorder.Stop(); // Writes some diagnostic information.
我想避免使用 RecorderWrapper 在我的所有“使用”范围块中尝试/捕获。有没有办法可以容纳“ReportFailure()”调用并仍然利用“使用”范围块?
具体来说,我希望我团队中的每个人都“陷入成功的陷阱”,即让做正确的事情变得容易。对我来说,这意味着很难忘记调用 recorder.Stop() 或忘记 try/catch。
谢谢!