本文介绍了Serilog记录器包装的实现和使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题与史蒂文的答案-.他提出了一个很好的记录器包装器.我将在下面粘贴他的代码:

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.
}

所以,我的问题是创建代理Serilog的实现的正确方法是什么?

So, my question is what is the proper way to create implementation that proxies to Serilog?

注意:此问题与有关log4net的问题但现在特定于Serilog.

Note: this question is related to this question about log4net but now specific to Serilog.

推荐答案

您应该创建类似以下内容的

you should create something like:

public class SerilogAdapter : ILogger
{
    private readonly Serilog.ILogger m_Adaptee;

    public SerilogAdapter(Serilog.ILogger adaptee)
    {
        m_Adaptee = adaptee;
    }

    public void Log(LogEntry entry)
    {
        if (entry.Severity == LoggingEventType.Debug)
            m_Adaptee.Debug(entry.Exception, entry.Message);
        if (entry.Severity == LoggingEventType.Information)
            m_Adaptee.Information(entry.Exception, entry.Message);
        else if (entry.Severity == LoggingEventType.Warning)
            m_Adaptee.Warning(entry.Message, entry.Exception);
        else if (entry.Severity == LoggingEventType.Error)
            m_Adaptee.Error(entry.Message, entry.Exception);
        else
            m_Adaptee.Fatal(entry.Message, entry.Exception);
    }
}

据我从史蒂文斯(Stevens)的答案中了解到:是的,您应该这样做.

As I understand from Stevens answer: Yes, you should do this.

如果使用的是DI容器,则只需使用DI容器将ILogger映射到SerilogAdapter.您还需要注册Serilog.ILogger,或者只是将Serilog logger的实例提供给DI容器,以将其注入SerilogAdapter构造函数.

If you are using a DI container, then just use the DI container to map ILogger to SerilogAdapter. You also need to register Serilog.ILogger, or just give an instance of Serilog logger to the DI container to inject it to the SerilogAdapter constructor.

如果您不使用DI容器,即使用纯DI ,然后您将执行以下操作:

If you don't use a DI container, i.e., you use Pure DI, then you do something like this:

Serilog.ILogger log = Serilog.Log.Logger.ForContext("MyClass");

ILogger logging_adapter = new SerilogAdapter(log);

var myobject = new MyClass(other_dependencies_here, logging_adapter);

这篇关于Serilog记录器包装的实现和使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 17:24