包裹Serilog.Exceptions
非常适合记录异常。它有大量支持的异常类型。
例如当前设置:
Log.Logger = new LoggerConfiguration()
.Enrich.WithExceptionDetails()
.CreateLogger();
目前,如果没有找到异常类型的解构器,它会回退到“基于反射的解构器”。
出于性能考虑,但更重要的是可预测性,我们希望禁用反射回退。
我尝试使用 DestructuringOptions
进行配置,例如禁用某些默认析构函数或将 DestructuringDepth 设置为 0
。
不幸的是,这些选项不起作用:
ReflectionBasedDestructr
不在默认析构函数列表中- 不允许将
DestructuringDepth
设置为0
(异常(exception))
知道如何为此配置 Serilog.Exceptions 吗?
最佳答案
我认为最好的选择是实现自己的ExceptionDecostructor
,如下所示:
public class FallbackExceptionDestructurer : ExceptionDestructurer
{
public override Type[] TargetTypes => new[]
{
typeof(Exception),
};
public override void Destructure(
Exception exception,
IExceptionPropertiesBag propertiesBag,
Func<Exception, IReadOnlyDictionary<string, object>> destructureException)
{
base.Destructure(exception, propertiesBag, destructureException);
}
}
这样,您将保留所有可用的解构器,并且基于反射的将被忽略,因为 FallbackExceptionDestructr
将覆盖由于以下代码而导致的所有未知异常:
public override Type[] TargetTypes => new[]
{
typeof(Exception),
};
这就是注册解构器的方式
.Enrich.WithExceptionDetails(new DestructuringOptionsBuilder()
.WithDefaultDestructurers()
.WithDestructurers(new[] { new FallbackExceptionDestructurer () }))
如果你查看ExceptionDestructurer.Decostruct(...)的源代码它不使用任何反射 - 仅使用 Exception 类型中众所周知的属性。
关于c# - 是否可以在 Serilog.Exceptions 中禁用基于反射的解构器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59054681/