使用通用主机时,在 NetCore 中使用 Serilog 配置日志记录的首选方法是什么?
What is the preferred way to configure logging with Serilog in NetCore when using a generic Host?
如果你想在 NetCore 和通用 Host
(或 IHost
)而不是 WebHost
或其他东西中使用它,应该如何配置 Serilog?
我找到了两个选项:
- 使用
Serilog.Extensions.Hosting
NuGet 包中的 .UseSerilog()
:
var host = Host.CreateDefaultBuilder()
.UseSerilog()
.UseSystemd()
.UseWindowsService()
.Build();
- 使用
Serilog
NuGet 包中的 .ConfigureLogging()
和 .AddSerilog()
:
.ConfigureLogging(
logging =>
{
logging.AddSerilog();
});
所以现在有两个问题:
- 这两个选项是否导致相同的行为,如果不是,有什么区别?
- 应该优先使用哪种方法(或者它们是否相等,您可以随意使用)?
从 Serilog.AspNetCore
(版本 5.0.0)开始,第二个选项被标记为已弃用,应使用通用主机选项(选项 1)。例如,使用虚拟主机构建器:
private static IHostBuilder CreateHostBuilder(string[] args, string currentLocation) =>
Host.CreateDefaultBuilder(args).ConfigureWebHostDefaults(
webBuilder =>
{
webBuilder.UseContentRoot(currentLocation);
webBuilder.UseStartup<Startup>();
})
.UseSerilog();
如果你想在 NetCore 和通用 Host
(或 IHost
)而不是 WebHost
或其他东西中使用它,应该如何配置 Serilog?
我找到了两个选项:
- 使用
Serilog.Extensions.Hosting
NuGet 包中的.UseSerilog()
:
var host = Host.CreateDefaultBuilder()
.UseSerilog()
.UseSystemd()
.UseWindowsService()
.Build();
- 使用
Serilog
NuGet 包中的.ConfigureLogging()
和.AddSerilog()
:
.ConfigureLogging(
logging =>
{
logging.AddSerilog();
});
所以现在有两个问题:
- 这两个选项是否导致相同的行为,如果不是,有什么区别?
- 应该优先使用哪种方法(或者它们是否相等,您可以随意使用)?
从 Serilog.AspNetCore
(版本 5.0.0)开始,第二个选项被标记为已弃用,应使用通用主机选项(选项 1)。例如,使用虚拟主机构建器:
private static IHostBuilder CreateHostBuilder(string[] args, string currentLocation) =>
Host.CreateDefaultBuilder(args).ConfigureWebHostDefaults(
webBuilder =>
{
webBuilder.UseContentRoot(currentLocation);
webBuilder.UseStartup<Startup>();
})
.UseSerilog();