简体   繁体   English

Serilog 最佳实践与例外

[英]Serilog best practices with exceptions

I use Serilog for diagnostics in my .NET Core 5 console application.我在 .NET Core 5 控制台应用程序中使用 Serilog 进行诊断。 I can't decide the best logging semantics in conjunction with exception handling.我无法确定与异常处理相结合的最佳日志记录语义。 For example, suppose I perform an operation that requires a file to exist.例如,假设我执行一个需要文件存在的操作。 If that file doesn't exist, I throw an exception for flow-control reasons (I need to unwind to properly exit the application).如果该文件不存在,我会出于流程控制的原因抛出异常(我需要展开以正确退出应用程序)。 But where and how do I log this?但是我在哪里以及如何记录这个? I can think of a few options:我能想到几个选择:

First option - Log before I throw:第一个选项 - 在我投掷之前记录:

if (!File.Exists(myFilePath)) {
  _logger.Error("The file does not exist: {File}", myFilePath);
  throw new ArgumentException("File does not exist", nameof(myFilePath));
}

Second option - Log the exception when its caught:第二个选项 - 在捕获异常时记录异常:

try {
  if (!File.Exists(myFilePath)) {
    throw new ArgumentException("File does not exist", nameof(myFilePath));
  }
}
catch (Exception e) {
  _logger.Error(e, "An Exception");
}

Code-wise, I like the second option best.代码方面,我最喜欢第二种选择。 As far as the descriptive strings themselves, I'm not repeating myself.至于描述性字符串本身,我不会重复自己。 However, I feel like the information is going to be communicated in different ways.但是,我觉得信息将以不同的方式传达。 I am not sure what the output of the second option looks like: Is it going to be structured?我不确定第二个选项的 output 是什么样的:它会被结构化吗? It's missing the original log string from the first option.它缺少第一个选项中的原始日志字符串。

Which way is best?哪种方式最好? Are there other options I should be considering?我应该考虑其他选择吗?

I've grappled with this question before, and here's where I landed.我之前已经解决过这个问题,这就是我着陆的地方。 Repeating yourself might not be an issue in practice: there are two events being captured, 1) a problem with the configuration file, and 2) an unhandled exception/application exit.在实践中重复自己可能不是问题:捕获了两个事件,1)配置文件有问题,2)未处理的异常/应用程序退出。

They're related, and they overlap a little, but they're not the same thing.它们是相关的,它们有一点重叠,但它们不是一回事。

Imagine reading the events like this:想象一下阅读这样的事件:

[ERR] Could not open configuration, the file ./foo.config does not exist
[FTL] An unhandled exception occurred, exiting the application
System.ArgumentException: The file ./foo.config does not exist
 at YourApp.OpenConfig(string filename)
 at ...

The first event: what went wrong?第一个事件:出了什么问题? Why was the file being opened in the first place?为什么文件首先被打开? This is the place to capture all of the detailed context.这是捕获所有详细上下文的地方。

The second event: why did the app exit?第二个事件:app为什么退出? Since no higher-level handler could deal with the exception - blat, here it all is in the log.由于没有更高级别的处理程序可以处理异常 - blat,所以这一切都在日志中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM