我配置了一个用来手动记录消息的记录器。
框架中的某些东西(Kestrel?)现在使用配置的记录器记录我不想要的未处理异常。
如何避免这种情况?
这是我的Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddTransient(serviceProvider => serviceProvider.GetService<ILoggerFactory>().CreateLogger(typeof(SentryLogger)));
RegisterConfigs(services, Configuration);
}
public void Configure(
IApplicationBuilder app,
IHostingEnvironment env,
IApplicationLifetime appLifetime,
ILoggerFactory loggerFactory,
ISentryConfig sentryConfig)
{
ConfigureLoggers(env, appLifetime, loggerFactory, sentryConfig);
if (env.IsDevelopment())
{
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
private static void ConfigureLoggers(IHostingEnvironment env,
IApplicationLifetime appLifetime,
ILoggerFactory loggerFactory,
ISentryConfig sentryConfig)
{
loggerFactory.AddSentry(sentryConfig, LogLevel.Error);
}
我的记录器
public static class LoggerFactoryExtensions
{
public static ILoggerFactory AddSentry(this ILoggerFactory factory, ISentryConfig config, LogLevel minLevel)
{
factory.AddProvider(new SentryLoggerProvider(config, minLevel));
return factory;
}
}
public class SentryLoggerProvider : ILoggerProvider
{
private readonly ISentryConfig _config;
private readonly LogLevel _minLevel;
public SentryLoggerProvider(ISentryConfig config, LogLevel minLevel)
{
_config = config;
_minLevel = minLevel;
}
public ILogger CreateLogger(string categoryName)
{
return new SentryLogger(_minLevel, _config.SentryDsn);
}
public void Dispose()
{ }
}
public class SentryLogger : ILogger
{
private readonly LogLevel _minLevel;
private readonly string _dsn;
public SentryLogger(LogLevel minLevel, string dsn)
{
_minLevel = minLevel;
_dsn = dsn;
}
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
if (!IsEnabled(logLevel)) return;
var sentryClient = new RavenClient(_dsn);
sentryClient.CaptureAsync(new SentryEvent(exception)
{
Message = state?.ToString() ?? string.Empty,
Level = LogLevelToSentryLevel(logLevel)
}).Wait();
}
public bool IsEnabled(LogLevel logLevel)
{
return logLevel >= _minLevel;
}
public IDisposable BeginScope<TState>(TState state)
{
return null;
}
private ErrorLevel LogLevelToSentryLevel(LogLevel level)
{
....
}
}