在 ASP.NET Core 3.1 中添加了一项功能,可以将未处理的异常传递到 ILogger 实例,如下所示: Logging in .NET Core and ASP.NET Core
我有一个服务器端 Blazor 网站,我希望能够在函数中处理这些异常,在该函数中我可以将它们记录到数据库或发送电子邮件。但是,我无法根据提供的文档提出执行此操作的代码。有人可以提供示例代码来捕获未处理的异常吗?
最佳答案
我建议使用Serilog配有您需要的水槽。
在您的项目中添加包:
dotnet add package Serilog.AspNetCore
dotnet add package Serilog.Settings.Configuration
dotnet add package Serilog.Sinks.Console
dotnet add package Serilog.Sinks.Debug
dotnet add package Serilog.Sinks.Seq
Serilog.AspNetCore将 Serilog 与 ASP.Net core 集成。
Serilog.Settings.Configuration从.Net核心配置中读取serilog配置。
Serilog.Sinks.Console在控制台中写入日志。
Serilog.Sinks.Debug在 Visual Studio 输出 Pane 中写入日志。
Serilog.Sinks.Seq将日志写入 Seq服务器,比数据库强大得多。
在您的Program.cs中设置登录:
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseSerilog((hostingContext, loggerConfiguration) => loggerConfiguration
.ReadFrom.Configuration(hostingContext.Configuration))
.Build();
在 Startup.cs 中:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Admin/Error");
}
app.UseSerilogRequestLogging()
并在 appsettings.json 中配置日志:
"Serilog": {
"LevelSwitches": {
"$controlSwitch": "Information"
},
"MinimumLevel": {
"ControlledBy": "$controlSwitch"
},
"WriteTo": [
{
"Name": "Seq",
"Args": {
"serverUrl": "http://localhost:5341/",
"controlLevelSwitch": "$controlSwitch",
"apiKey": "{SeqApiKey}"
}
},
{
"Name": "Console"
},
{
"Name": "Debug"
}
],
"Enrich": [
"FromLogContext",
"WithMachineName",
"WithThreadId"
]
}
这告诉 Serilog 使用 Seq 中为您的应用配置的日志级别。
"LevelSwitches": {
"$controlSwitch": "Information"
}
...
"Args": {
"serverUrl": "http://localhost:5341/",
"controlLevelSwitch": "$controlSwitch",
"apiKey": "{SeqApiKey}"
}
{SeqApiKey}
是在 Seq 服务器中为您的应用配置的 Api key 。
如果你想使用DB,Serilog有long list of sinks你可以使用。
关于asp.net-core - 处理 ASP.NET Core 3.1 中未处理的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59413587/