簡體   English   中英

是否可以在 Serilog.Exceptions 中禁用基於反射的解構器?

[英]Is it possible to disabled the reflection based destructurer in Serilog.Exceptions?

Serilog.Exceptions包非常適合記錄異常。 它有大量支持的異常類型。

例如當前設置:

Log.Logger = new LoggerConfiguration()
    .Enrich.WithExceptionDetails()
    .CreateLogger();

目前,如果沒有找到異常類型的解構器,它會回退到“基於反射的解構器”。

由於性能,但更重要的是可預測性,我們希望禁用反射回退。

我嘗試使用DestructuringOptions配置它,例如禁用一些默認析構函數或將 DestructuringDepth 設置為0

不幸的是,這些選項不起作用:

  • ReflectionBasedDestructurer不在默認析構函數列表中
  • 不允許將DestructuringDepth設置為0 (例外)

知道如何為此配置 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);
        }
 }

這樣您將保留所有可用的解構器,並且基於反射的將被忽略,因為FallbackExceptionDestructurer將覆蓋由於此代碼引起的所有未知異常:

public override Type[] TargetTypes => new[]
{
  typeof(Exception),
};

這就是你注冊解構器的方式

.Enrich.WithExceptionDetails(new DestructuringOptionsBuilder()
    .WithDefaultDestructurers()
    .WithDestructurers(new[] { new FallbackExceptionDestructurer () }))

如果您檢查ExceptionDestructurer.Decostruct(...)的源代碼,它不使用任何反射 - 僅使用 Exception 類型的眾所周知的屬性。

這已添加到 Serilog.Exceptions 5.4.0,請參閱變更日志 有一個新方法WithoutReflectionBasedDestructurer

用法

輔助類

public static class LoggerEnrichmentConfigurationExtensions
{
    public static LoggerConfiguration WithExceptionDetailsWithoutReflection(
        this LoggerEnrichmentConfiguration loggerEnrichmentConfiguration)
    {
        if (loggerEnrichmentConfiguration is null)
        {
            throw new ArgumentNullException(nameof(loggerEnrichmentConfiguration));
        }
        var options = new DestructuringOptionsBuilder()
            .WithDefaultDestructurers()
            .WithoutReflectionBasedDestructurer() //new in 5.4.0!
            .WithIgnoreStackTraceAndTargetSiteExceptionFilter();
        var logEventEnricher = new ExceptionEnricher(options);
        return loggerEnrichmentConfiguration.With(logEventEnricher);
    }
}

配置

Log.Logger = new LoggerConfiguration()
                .ReadFrom.Configuration(configuration)
                .Enrich.WithExceptionDetailsWithoutReflection()
                .CreateLogger();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM