在 Serilog 中记录异常时减少堆栈跟踪帧的数量

问题描述 投票:0回答:1

在 ASP.NET 中记录异常时,堆栈跟踪通常会与您的手臂一样长。例如,我不需要完整的堆栈跟踪在数据库中找不到实体。我想限制它 - 要么仅限于堆栈跟踪的第一帧,要么如果不可能,则仅限于异常消息。

我正在将 Serilog 与 ASP.NET (Core) 8.0 一起使用。目前我们正在记录到纯文本文件。

我的记录器配置如下:

    builder.Host.UseSerilog((context, services, configuration) => configuration
        .ReadFrom.Configuration(context.Configuration)
        .ReadFrom.Services(services)
        .Enrich.FromLogContext());

在 application.json 中:

  "Serilog": {
    "Using":  [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ],
    "MinimumLevel": { 
      "Default" : "Information",
      "Override": {
        "Microsoft": "Warning",
        "System": "Warning",
        "Microsoft.EntityFrameworkCore.Database.Command": "Fatal"
      } 
    },
    "WriteTo": [
      { "Name": "Console" },
      { "Name": "File", "Args": { "path":  "./logs/log-.txt", "rollingInterval": "Day" } }
    ],
    "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ],
    "Destructure": [
      { "Name": "ToMaximumDepth", "Args": { "maximumDestructuringDepth": 4 } },
      { "Name": "ToMaximumStringLength", "Args": { "maximumStringLength": 100 } },
      { "Name": "ToMaximumCollectionCount", "Args": { "maximumCollectionCount": 10 } }
    ]
  },

我希望

maximumDestructuringDepth
能够覆盖它,但事实似乎并非如此。

c# asp.net serilog
1个回答
0
投票

这应该适合你,在你的program.cs中配置serilog

builder.Host.UseSerilog((context, services, configuration) => {
    configuration.ReadFrom.Configuration(context.Configuration)
                 .ReadFrom.Services(services)
                 .Enrich.FromLogContext();
    Log.Logger = new LoggerConfiguration()
        .ReadFrom.Configuration(builder.Configuration)
        .Enrich.FromLogContext()
        .CreateLogger();
});

创建自定义异常格式化程序

public static class CustomExceptionFormatter
{
    public static string FormatException(Exception exception)
    {
        if (exception == null) return string.Empty;

        var stackTrace = new StackTrace(exception, fNeedFileInfo: true);
        var firstFrame = stackTrace.FrameCount > 0 ? stackTrace.GetFrame(0) : null;

        string formattedMessage = $"{exception.Message}";
        if (firstFrame != null)
        {
            formattedMessage += $" at {firstFrame.GetMethod()} in {firstFrame.GetFileName()}:line {firstFrame.GetFileLineNumber()}";
        }
        return formattedMessage;
    }
}

还有测试仪

    [HttpGet]
    public ActionResult Get()
    {
        try
        {
            
            throw new InvalidOperationException("Test exception");
        }
        catch (Exception ex)
        {
            var formattedException = CustomExceptionFormatter.FormatException(ex);
            Log.Error(ex, "{FormattedException}", formattedException);
            return Problem(detail: formattedException);
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.