Microsoft.Extensions.Logging的记录器包装程序的实现和使用 [英] Implementation and usage of logger wrapper for Microsoft.Extensions.Logging
问题描述
此问题与史蒂文的答案-
This question is related to Steven’s answer - here. He proposed a very good logger wrapper. I will paste his code below:
public interface ILogger
{
void Log(LogEntry entry);
}
public static class LoggerExtensions
{
public static void Log(this ILogger logger, string message)
{
logger.Log(new LogEntry(LoggingEventType.Information,
message, null));
}
public static void Log(this ILogger logger, Exception exception)
{
logger.Log(new LogEntry(LoggingEventType.Error,
exception.Message, exception));
}
// More methods here.
}
所以,我的问题是创建替代Microsoft.Extensions.Logging的实现的正确方法是什么和稍后在代码中使用它的最佳方法是什么 >?
So, my question is what is the proper way to create implementation that proxies to Microsoft.Extensions.Logging and what is the best way to use it later in the code?
注意:此问题是关于log4net的问题的副本,但现在特定于Microsoft.Extensions.Logging.
Note: this question is a copy of this question about log4net but now specific to Microsoft.Extensions.Logging.
推荐答案
所以,我的问题是创建代理到Microsoft.Extensions.ILogger的实现的正确方法是什么?
So, my question is what is the proper way to create implementation that proxies to Microsoft.Extensions.ILogger?
您应该创建类似以下内容的
you should create something like:
public sealed class MicrosoftLoggingAdapter : ILogger
{
private readonly Microsoft.Extensions.ILogger adaptee;
public MicrosoftLoggingAdapter (Microsoft.Extensions.ILogger adaptee) =>
this.adaptee = adaptee;
public void Log(LogEntry e) =>
adaptee.Log(ToLevel(e.Severity), 0, e.Message, e.Exception, (s, _) => s);
private static LogLevel ToLevel(LoggingEventType s) =>
s == LoggingEventType.Debug ? LogLevel.Debug :
s == LoggingEventType.Information ? LogLevel.Information :
s == LoggingEventType.Warning ? LogLevel.Warning :
s == LoggingEventType.Error ? LogLevel.Error :
LogLevel.Critical;
}
稍后在代码中使用它的最佳方法是什么?
what is the best way to use it later in the code?
如果使用的是DI容器,则只需使用DI容器将ILogger
映射到MicrosoftLoggingAdapter
.您还需要注册Microsoft.Extensions.ILogger
,或者只是将MS记录器的实例提供给DI容器,以将其注入到MicrosoftLoggingAdapter构造函数中.
If you are using a DI container, then just use the DI container to map ILogger
to MicrosoftLoggingAdapter
. You also need to register Microsoft.Extensions.ILogger
, or just give an instance of MS logger to the DI container to inject it to the MicrosoftLoggingAdapter constructor.
如果您不使用DI容器,即使用纯DI ,然后您将执行以下操作:
If you don't use a DI container, i.e., you use Pure DI, then you do something like this:
var logger = loggerFactory.CreateLogger("Application");
ILogger logging_adapter = new MicrosoftLoggingAdapter(logger);
var myobject = new MyClass(other_dependencies_here, logging_adapter);
这篇关于Microsoft.Extensions.Logging的记录器包装程序的实现和使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!