Serilog.Exceptionsログの例外の詳細と、Exception.ToString() に出力されないカスタム プロパティを参照してください。
このライブラリには、最も一般的な例外タイプの追加プロパティを処理するカスタム コードが含まれており、例外が Serilog.Exceptions によって内部的にサポートされていない場合にのみ、リフレクションを使用して追加情報を取得します。
NuGet パッケージを追加してから、次のようにエンリッチャーを追加します。
using Serilog;
using Serilog.Exceptions;
ILogger logger = new LoggerConfiguration()
.Enrich.WithExceptionDetails()
.WriteTo.Sink(new RollingFileSink(
@"C:\logs",
new JsonFormatter(renderMessage: true))
.CreateLogger();
JSON ログは、詳細な例外情報とカスタム例外プロパティで補完されるようになりました。EntityFramework から DbEntityValidationException をログに記録するとどうなるかの例を次に示します (この例外は、 に含まれていない深くネストされたカスタム プロパティを持つことで有名です.ToString()
)。
try
{
...
}
catch (DbEntityValidationException exception)
{
logger.Error(exception, "Hello World");
}
上記のコードは、次のログを記録します。
{
"Timestamp": "2015-12-07T12:26:24.0557671+00:00",
"Level": "Error",
"MessageTemplate": "Hello World",
"RenderedMessage": "Hello World",
"Exception": "System.Data.Entity.Validation.DbEntityValidationException: Message",
"Properties": {
"ExceptionDetail": {
"EntityValidationErrors": [
{
"Entry": null,
"ValidationErrors": [
{
"PropertyName": "PropertyName",
"ErrorMessage": "PropertyName is Required.",
"Type": "System.Data.Entity.Validation.DbValidationError"
}
],
"IsValid": false,
"Type": "System.Data.Entity.Validation.DbEntityValidationResult"
}
],
"Message": "Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.",
"Data": {},
"InnerException": null,
"TargetSite": null,
"StackTrace": null,
"HelpLink": null,
"Source": null,
"HResult": -2146232032,
"Type": "System.Data.Entity.Validation.DbEntityValidationException"
},
"Source": "418169ff-e65f-456e-8b0d-42a0973c3577"
}
}
Serilog.Exceptionsは .NET Standard をサポートし、リフレクションなしで多くの一般的な例外タイプをサポートしていますが、さらに追加したいと考えているため、お気軽に貢献してください。
重要なヒント - 人間が読めるスタック トレース
Ben.Demystifier NuGet パッケージを使用して、人間が判読できる例外のスタック トレースを取得するか、 Serilog を使用している場合はserilog-enrichers-demystify NuGet パッケージを使用できます。