如何让Sentry忽略一些异常?

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

我正在使用 Serilog 将异常记录到 Sentry。我想忽略一些异常并且不将它们记录到 Sentry。如果可能的话,我想从应用程序设置文件中读取这些异常。我尝试过这个,但没有成功。我在这里尝试忽略 NotImplementedException 异常。

应用程序设置.json

{
  "Logfile": {
    "Name": "/logs/log-Service-.txt"
  },
  "Sentry": {
    "Dsn": "https://sentry.dns"
  },
  "Serilog": {
    "IgnoreList": {
      "ExceptionTypes": [
        "NotImplementedException"
      ]
    }
  },
  "ConnectionStrings": {
    "DefaultConnection": "myconnection"
  }
}

HostBuilderExtensions.cs

    public static class HostBuilderExtensions
    {
        public static IHostBuilder UseCustomSerilog(this IHostBuilder builder, IConfiguration configuration)
        {
            var ignoreList = configuration.GetSection("Serilog:IgnoreList:ExceptionTypes")
            .Get<string[]>() ?? Array.Empty<string>();

            return builder.UseSerilog((context, config) =>
            {
                config.MinimumLevel.Verbose()
                    .MinimumLevel.Override("Microsoft", LogEventLevel.Fatal)
                    .WriteTo.Udp(
                        remoteAddress: configuration.GetSection("Logstash")["Host"] ?? throw new InvalidOperationException(),
                        remotePort: int.Parse(configuration.GetSection("Logstash")["Port"] ?? throw new InvalidOperationException()),
                        family: AddressFamily.InterNetwork, formatter: new CompactJsonFormatter()
                    )
                    .Enrich.WithProperty("type", configuration.GetSection("Logstash")["Type"] ?? throw new InvalidOperationException())
                    .WriteTo.File(
                        new CompactJsonFormatter(),
                        configuration.GetSection("Logfile")["Name"] ?? throw new InvalidOperationException(),
                        rollingInterval: RollingInterval.Day
                    )
                    .WriteTo.Console()
                    .WriteTo.Sentry(o =>
                    {
                        o.Dsn = configuration.GetSection("Sentry")["Dns"];
                        o.MinimumEventLevel = LogEventLevel.Error;
                        o.MinimumBreadcrumbLevel = LogEventLevel.Error;
                        o.SetBeforeSend((sentryEvent, _) =>
                        {
(exceptionsToIgnore.Contains(sentryEvent.Exception?.GetType().FullName))
                            if (ignoreList.Contains(sentryEvent.Exception?.GetType().FullName))
                            {
                                Console.WriteLine("Ignored");
                                return null;
                            }

                            return sentryEvent;
                        });
                        //o.AddExceptionFilterForType<NotImplementedException>();
                    })
                    .Enrich.FromLogContext();
            });
        }
    }

程序.cs

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

builder.WebHost.UseSentry();

builder.Host.UseCustomSerilog(builder.Configuration);

var app = builder.Build();

app.UseSwagger();

app.UseSwaggerUI(c =>
{
    string swaggerJsonBasePath = string.IsNullOrWhiteSpace(c.RoutePrefix) ? "." : "..";
    c.SwaggerEndpoint($"{swaggerJsonBasePath}/swagger/v1/swagger.json", "Bet");
});

app.UseHttpsRedirection();

app.UseAuthorization();

app.UseMiddleware<GlobalExceptionHandling>();

app.UseMiddleware<GlobalLoggerHandling>();

app.UseMiddleware<ValidationMiddleware>();

app.MapControllers();

app.Run();

它仍然记录异常。

谢谢

c# serilog sentry
1个回答
0
投票

Sentry 代码库有一个 如何忽略特定类型的异常的示例

class ExceptionTypeFilter<TException> : IExceptionFilter where TException : Exception
{
    private readonly Type _filteredType = typeof(TException);
    public bool Filter(Exception ex) => _filteredType.IsInstanceOfType(ex);
}

您可以在配置 Sentry 时将其连接起来,例如:

SentrySdk.Init(options => {
    // All your other config here...
    options.AddExceptionFilter(new ExceptionTypeFilter<NotImplementedException>());
});

您显然可以对其进行修改以执行更奇特的操作,并且您发现的

SetBeforeSend
回调事件是更一般地过滤事件(不仅仅是异常事件)的好选择。

在无法在调试器中运行代码的情况下(希望这种情况很少见),日志记录可能会有所帮助。您还可以/应该尝试在部署代码之前使用单元测试来测试您的代码。但理想情况下,您将希望能够在调试器中运行一些东西来理解事物。

© www.soinside.com 2019 - 2024. All rights reserved.