简体   繁体   中英

Serilog best practices with exceptions

I use Serilog for diagnostics in my .NET Core 5 console application. 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? 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.

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? Since no higher-level handler could deal with the exception - blat, here it all is in the log.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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