简体   繁体   English

如何使用 serilog 自定义异常输出

[英]How to customize exception output using serilog

I'm using Serilog as my logging framework (with Seq as my log sink).我使用 Serilog 作为我的日志框架(使用 Seq 作为我的日志接收器)。 When logging exceptions I'm using something like:在记录异常时,我使用的是类似的东西:

log.Error(ex, "Operation Failed");

My application makes heavy use of async/await methods.我的应用程序大量使用 async/await 方法。 When unhandled exceptions occur the stack traces are very hard to read.当发生未处理的异常时,堆栈跟踪非常难以阅读。 There is a nuget package that cleans up async stack traces ( https://github.com/aelij/AsyncFriendlyStackTrace ).有一个 nuget 包可以清理异步堆栈跟踪 ( https://github.com/aelij/AsyncFriendlyStackTrace )。 This creates an extension method to give you access to a modified/clean stack trace:这将创建一个扩展方法,让您可以访问修改后的/干净的堆栈跟踪:

ex.ToAsyncString()

I'd like to be able to use this library to intercept the stack trace before it is written to Seq and instead log the clean/modified stack trace.我希望能够在将堆栈跟踪写入 Seq 之前使用该库拦截堆栈跟踪,并记录干净/修改后的堆栈跟踪。

Is there a way with Serilog/Seq to control the exact output of the error string that is sent to the log sink? Serilog/Seq 有没有办法控制发送到日志接收器的错误字符串的确切输出?

Perhaps enrichment might be helpful here.也许充实在这里可能会有所帮助。 While not specifically discussed in that link, you can build custom enrichers:虽然在该链接中没有具体讨论,但您可以构建自定义丰富器:

public class ExceptionEnricher : ILogEventEnricher
{
    public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
    {
        if (logEvent.Exception != null)
        {
            // do something here

            propertyFactory.CreateProperty("ExtraExceptionDetail", extraDetail);
        }
    }
}

then...然后……

var loggerConfig = new LoggerConfiguration()
    .MinimumLevel.Debug()
    .WriteTo.Seq(url)
    .Enrich.With<ExceptionEnricher>()
    .Enrich.FromLogContext();

I don't have any experience with the package you referenced, but this approach lets you intercept and modify/add/remove properties of the event before it's written to Seq.我对您引用的包没有任何经验,但是这种方法可以让您在将事件写入 Seq 之前拦截和修改/添加/删除事件的属性。

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

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