简体   繁体   English

将 Serilog 与 Microsoft.Extensions.Logging.ILogger 结合使用

[英]Use Serilog with Microsoft.Extensions.Logging.ILogger

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 .我已经使用主机创建了一个 .NET Core 3.1 项目,它是带有IServiceCollection IoC 容器,并使用来自Microsoft.Extensions.LoggingILogger<T>接口实现了整个地方的日志记录。 I now need to implement more advanced logging and decided to use Serilog.我现在需要实现更高级的日志记录并决定使用 Serilog。

I assumed that it would be a breeze to switch from .NET built-in loggers to Serilog.我认为从 .NET 内置记录器切换到 Serilog 会轻而易举。 But to my surprise, Serilog is using it's own ILogger interface - bummer!但令我惊讶的是,Serilog 正在使用它自己的ILogger接口——真可惜! So now I needed to update ALL places to use Serilog ILogger , or to implement Serilog with a .NET Core ILogger<T> interface.所以现在我需要更新所有地方以使用 Serilog ILogger ,或者使用 .NET Core ILogger<T>接口实现 Serilog。

My question is - is it really not possible to use Serilog with the ILogger interface in Microsoft.Extensions.Logging ?我的问题是 - 真的不可能在Microsoft.Extensions.Logging中将 Serilog 与 ILogger 接口一起使用吗? Would be so much smarter!会更聪明!

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.Serilog.Extensions.Logging程序集中, IloggingBuilder上有一个名为AddSerilog的扩展方法(它位于 Serilog 命名空间中),它允许您使用 Serilog 进行日志记录。 For example:例如:

.NET Core 2.2 and earlier (using WebHost ): .NET Core 2.2 及更早版本(使用WebHost ):

WebHost.CreateDefaultBuilder(args)
    .ConfigureLogging(logging =>
    {
        logging.ClearProviders();
        logging.AddSerilog();
    });

.NET Core 3.1 and later (using generic Host for either web or console apps): .NET Core 3.1 及更高版本(对 web 或控制台应用程序使用通用Host ):

Host.CreateDefaultBuilder(args)
    .ConfigureWebHostDefaults(webBuilder => webBuilder.UseStartup<Startup>()})
    .UseSerilog();

Now the ILogger and ILogger<> implementation will call into Serilog.现在ILoggerILogger<>实现将调用 Serilog。

For .NET 6 and later对于 .NET 6 及更高版本

using Serilog;

var builder = WebApplication.CreateBuilder(args);

builder.Host.UseSerilog((ctx, lc) => lc
    .WriteTo.Console()
    .ReadFrom.Configuration(ctx.Configuration));

Reference: Here参考:这里

In addition to ways by using builder.host.UseSeriLog() extensions method.除了使用builder.host.UseSeriLog()扩展方法的方法。 Here is more elegant way (we can use in external console or unit test ILogger without implementation of main project) .这是更优雅的方式(我们可以在外部控制台或单元测试 ILogger 中使用而无需执行主项目)

  1. Install Nuget Package Serilog.Extensions.Logging along with core package Serilog .安装 Nuget Package Serilog.Extensions.Logging以及核心 package Serilog
  2. Initialize Logger Configuration like you already doing.像您已经在做的那样初始化记录器配置。 For example a typical logging configuration would be write to Console would be like Log.Logger = new LoggerConfiguration).WriteTo.Console().CreateLogger() .例如,一个典型的日志记录配置将被写入控制台,就像Log.Logger = new LoggerConfiguration).WriteTo.Console().CreateLogger()一样。
  3. Use ILoggerFactory extension method AddSeriLog() like this ILoggerFactory factory = new LoggerFactory().AddSerilog(Log.Logger);像这样使用ILoggerFactory扩展方法AddSeriLog() ILoggerFactory factory = new LoggerFactory().AddSerilog(Log.Logger);
  4. Simply return factory.CreateLogger<T>();只需返回factory.CreateLogger<T>();
public static Microsoft.Extensions.Logging.ILogger LoggingInstance<T>()
{
  Serilog.Log.Logger = Serilog.Log.Logger ?? new LoggerConfiguration().WriteTo.(xxxxYourSinksxxxx).CreateLogger();
  ILoggerFactory factory = new LoggerFactory().AddSerilog(Log.Logger);            
  return factory.CreateLogger<T>();
}

Its usage be like它的用法就像

var logger = LoggingInstance<YourModel>();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 实例化后,Microsoft.Extensions.Logging.ILogger的模拟为null - Mock of Microsoft.Extensions.Logging.ILogger is null after instantiation 将本机日志机制转发到 C# Microsoft.Extensions.Logging.ILogger - Forwarding native logging mechanism to C# Microsoft.Extensions.Logging.ILogger 两个派生类如何共享 Microsoft.Extensions.Logging.ILogger<T> 日志框架? - How can a two derived classes share the Microsoft.Extensions.Logging.ILogger<T> logging framework? 无法解析“Microsoft.Extensions.Logging.ILogger`1[WebApplication1.Startup]”类型的服务 - Unable to resolve service for type 'Microsoft.Extensions.Logging.ILogger`1[WebApplication1.Startup]' 尝试激活“控制器”时无法解析“Microsoft.Extensions.Logging.ILogger”类型的服务 - Unable to resolve service for type 'Microsoft.Extensions.Logging.ILogger' while attempting to activate 'Controller' 如何为每个命名空间配置Microsoft.Extensions.Logging.ILogger级别? - How do I configure Microsoft.Extensions.Logging.ILogger levels per namespace? System.InvalidOperationException: &#39;无法解析类型&#39;Microsoft.Extensions.Logging.ILogger`1 的服务 - System.InvalidOperationException: 'Unable to resolve service for type 'Microsoft.Extensions.Logging.ILogger`1 "<i>Resolve generic Microsoft.Extensions.Logging.ILogger<\/i>解决通用 Microsoft.Extensions.Logging.ILogger<\/b><T> <i>with Unity - get InvalidCastException<\/i>使用 Unity - 获取 InvalidCastException<\/b>" - Resolve generic Microsoft.Extensions.Logging.ILogger<T> with Unity - get InvalidCastException &#39;尝试激活&#39;Application.Startup&#39;时无法解析类型&#39;Microsoft.Extensions.Logging.ILogger`1[Application.Startup]&#39;的服务。&#39; - 'Unable to resolve service for type 'Microsoft.Extensions.Logging.ILogger`1[Application.Startup]' while attempting to activate 'Application.Startup'.' Serilog 模板和 Microsoft.Extensions.Logging - Serilog templates and Microsoft.Extensions.Logging
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM