将 Serilog 与 Microsoft.Extensions.Logging.ILogger 结合使用 [英] Use Serilog with Microsoft.Extensions.Logging.ILogger
问题描述
我已经使用 Host 创建了一个 .NET Core 3.1 项目,这是一个带有 IServiceCollection
的 IoC 容器,并使用 ILogger
接口在整个地方实现了日志记录.Microsoft.Extensions.Logging
.我现在需要实现更高级的日志记录并决定使用 Serilog.
I've created a .NET Core 3.1 project using a Host, the IoC container with IServiceCollection
and implemented logging allover the place using the ILogger<T>
interface from Microsoft.Extensions.Logging
. I now need to implement more advanced logging and decided to use Serilog.
我认为从 .NET 内置记录器切换到 Serilog 会轻而易举.但令我惊讶的是,Serilog 正在使用它自己的 ILogger
接口 - 太糟糕了!所以现在我需要更新所有地方以使用 Serilog ILogger
,或者使用 .NET Core ILogger
接口实现 Serilog.
I assumed that it would be a breeze to switch from .NET built-in loggers to Serilog. But to my surprise, Serilog is using it's own ILogger
interface - bummer! So now I needed to update ALL places to use Serilog ILogger
, or to implement Serilog with a .NET Core ILogger<T>
interface.
我的问题是 - 真的不可能在 Microsoft.Extensions.Logging
中使用带有 ILogger 接口的 Serilog 吗?会更聪明!
My question is - is it really not possible to use Serilog with the ILogger interface in Microsoft.Extensions.Logging
? Would be so much smarter!
推荐答案
在 Serilog.Extensions.Logging
程序集中,IloggingBuilder
上有一个名为 的扩展方法AddSerilog
(它在 Serilog 命名空间中)将允许您使用 Serilog 进行日志记录.例如:
In the Serilog.Extensions.Logging
assembly there is a extension method on IloggingBuilder
called AddSerilog
(it's in the Serilog namespace) that will allow you to use Serilog for logging. For example:
.NET Core 2.2 及更早版本(使用 WebHost
):
.NET Core 2.2 and earlier (using WebHost
):
WebHost.CreateDefaultBuilder(args)
.ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.AddSerilog();
});
.NET Core 3.1 及更高版本(对 Web 或控制台应用程序使用通用 Host
):
.NET Core 3.1 and later (using generic Host
for either web or console apps):
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder => webBuilder.UseStartup<Startup>()})
.UseSerilog();
现在 ILogger
和 ILogger<>
实现将调用 Serilog.
Now the ILogger
and ILogger<>
implementation will call into Serilog.
这篇关于将 Serilog 与 Microsoft.Extensions.Logging.ILogger 结合使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!