简体   繁体   English

如何从 Serilog.ILogger 创建 MELA.ILogger 以在 .NET 标准库中使用

[英]How to create a MELA.ILogger from a Serilog.ILogger for use in a .NET Standard library

I am converting a .NET Standard utility library from console logging to ILogger logging.我正在将 .NET 标准实用程序库从控制台日志记录转换为ILogger日志记录。

The library consists static utility classes, and I am exposing a static ILogger property to be set by users, to point to whatever logging system they want to use.该库包含 static 实用程序类,我公开了一个 static ILogger属性,由用户设置,以指向他们想要使用的任何日志记录系统。

I want my .NET Core 3.1 and .NET 5 console apps to use Serilog for logging, and assign the library ILogger to Serilog, with all the goodness that comes with Serilog.我希望我的 .NET Core 3.1 和 .NET 5 控制台应用程序使用 Serilog 进行日志记录,并将库ILogger分配给 Serilog,并具有 Serilog 附带的所有优点。 I am not using DI in the utility library, as it is static methods, not "service" classes.我没有在实用程序库中使用 DI,因为它是 static 方法,而不是“服务”类。

How do I manually (not using DI) create a Microsoft.Extensions.Logging.ILogger from a Serilog.ILogger or a Serilog.Extensions.Logging.SerilogLoggerFactory .如何手动(不使用 DI)从Serilog.ILoggerSerilog.Extensions.Logging.SerilogLoggerFactory创建Microsoft.Extensions.Logging.ILogger

Any suggestions on an easier way vs. the example code?关于更简单的方法与示例代码的任何建议?

// How to create a "Microsoft.Extensions.Logging.ILogger" from a "Serilog.ILogger"?
Microsoft.Extensions.Logging.ILogger logger = Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance;

// https://github.com/serilog/serilog-extensions-logging/blob/dev/samples/Sample/Program.cs
LoggerProviderCollection providerCollection = new LoggerProviderCollection();

Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Debug()
    .Enrich.FromLogContext()
    .WriteTo.Console()
    .WriteTo.Providers(providerCollection)
    .CreateLogger();

ServiceCollection serviceCollection = new ServiceCollection();
serviceCollection.AddSingleton(providerCollection);
serviceCollection.AddSingleton<ILoggerFactory>(sc =>
{
    LoggerProviderCollection loggerProviderCollection = sc.GetService<LoggerProviderCollection>();
    SerilogLoggerFactory serilogLoggerFactory = new SerilogLoggerFactory(null, true, loggerProviderCollection);

    foreach (ILoggerProvider loggerProvider in sc.GetServices<ILoggerProvider>())
        serilogLoggerFactory.AddProvider(loggerProvider);

    return serilogLoggerFactory;
});

serviceCollection.AddLogging(logging => logging.AddConsole());

ServiceProvider serviceProvider = serviceCollection.BuildServiceProvider();
ILogger<Program> programLogger = serviceProvider.GetRequiredService<ILogger<Program>>();

logger = programLogger;
logger.LogInformation("Testing testing");

I found a solution with simpler code:我找到了一个代码更简单的解决方案:

// https://www.nexmo.com/legacy-blog/2020/02/10/adaptive-library-logging-with-microsoft-extensions-logging-dr

// Default : "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}"

// Serilog logger
Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Debug()
    .WriteTo.Console(outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} {Level} {SourceContext} | {Message:lj}{NewLine}{Exception}", 
                        theme: AnsiConsoleTheme.Code)
    .CreateLogger();

// MEL logger factory
LoggerFactory loggerFactory = new LoggerFactory();
loggerFactory.AddSerilog(Log.Logger);

// MEL logger
Microsoft.Extensions.Logging.ILogger logger = loggerFactory.CreateLogger("Foo");
logger.LogInformation("Testing testing");

The following worked for me.以下对我有用。

// existing serilog logger
Serilog.ILogger logger = Log.ForContext<MyType>();

// create MEL logger from serilog logger
var loggerFactory = new Microsoft.Extensions.Logging.LoggerFactory();
loggerFactory.AddSerilog(logger);
var melLogger = loggerFactory.CreateLogger<MyType>();

// sample log message
melLogger.LogInformation("Sample log message");

Related NuGet packages:相关 NuGet 封装:

  • Serilog - for serilog Serilog - 用于 Serilog
  • Serilog.Extensions.Logging - for AddSerilog method Serilog.Extensions.Logging - 用于 AddSerilog 方法
  • Microsoft.Extensions.Logging - for LogInformation method Microsoft.Extensions.Logging - 用于 LogInformation 方法
  • Microsoft.Extensions.LoggingAbstractions - for logging factory Microsoft.Extensions.LoggingAbstractions - 用于日志工厂

Serilog was configured in a separate project, that project included the Serilog.AspNetCore NuGet package only. Serilog 在一个单独的项目中配置,该项目仅包括 Serilog.AspNetCore NuGet package。

The reason why I needed to make a MEL logger was due to a 3rd party library.我需要制作 MEL 记录器的原因是由于第 3 方库。 That library only accepted an MEL logger provider.该库仅接受 MEL 记录器提供程序。 This solution did not use dependency injection for the ILogger, so I had to do the conversion.这个解决方案没有对 ILogger 使用依赖注入,所以我必须进行转换。

Here's the simplest way I could find:这是我能找到的最简单的方法:

Using Serilog;

Then in your method.然后在你的方法中。 Note: The melLogger in the snippet below is a new instance of the logger注意:下面代码段中的 melLogger 是记录器的新实例

Log.Logger = new LoggerConfiguration()
    .Enrich.FromLogContext()
    .WriteTo.Debug(restrictedToMinimumLevel: LogEventLevel.Verbose)
    .CreateLogger();

Microsoft.Extensions.Logging.ILogger melLogger= new SerilogLoggerProvider(Log.Logger)
                                               .CreateLogger("WHATVER_YOU_WANT");

Then to use this system wide via dependency injection, the secret sauce being.UseSeriLog():然后通过依赖注入在整个系统范围内使用这个系统,秘诀是.UseSeriLog():

Host.CreateDefaultBuilder()
    .UseSerilog()                
    .ConfigureWebHostDefaults(webBuilder =>
    {
        webBuilder.UseStartup(typeof(StartUp));
    });

暂无
暂无

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

相关问题 使用静态`Serilog.ILogger`是否安全 - Is it safe to use a static `Serilog.ILogger` 在 Azure Function 中使用 Serilog.ILogger - Using Serilog.ILogger in Azure Function ASP.NET Core Web API - 尝试激活“AuthService”时无法解析“Serilog.ILogger”类型的服务 - ASP.NET Core Web API - Unable to resolve service for type 'Serilog.ILogger' while attempting to activate 'AuthService' 如何在具有 singleton 模式的 .NET 库中使用 ILogger 抽象? - How can I use ILogger abstractions in a .NET Library with a singleton pattern? 无法解析“Serilog.ILogger”类型的服务:“AspNetCore.Serilog.RequestLoggingMiddleware” - Unable to resolve service for type 'Serilog.ILogger' : "AspNetCore.Serilog.RequestLoggingMiddleware" 将 Serilog 与 Microsoft.Extensions.Logging.ILogger 结合使用 - Use Serilog with Microsoft.Extensions.Logging.ILogger 如何从 .NET Framework 初始化 .net Core ILogger 或 ILoggerFactory 并注入 Class 内置库中的构造函数.Net Core - How to initialize .net Core ILogger or ILoggerFactory from .NET Framework and inject to a constructor in Class library built in .Net Core 如何使用 ILogger<class> 在没有 DI 的 Class 库中</class> - How to use ILogger<Class> in a Class Library without DI 运行Asp.Net Core 2的Webapi 2上带有Seri​​log的DI ILogger - DI ILogger with Serilog on Webapi 2 running Asp.Net Core 2 Serilog 使用 Microsoft ILogger - 从 .NET Core 中的一个代码记录到不同的位置 - Serilog using Microsoft ILogger - logging to different places from one code in .NET Core
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM