Serilog logger wrapper 的实现和使用

Implementation and usage of logger wrapper for Serilog

此问题与 Steven’s answer - here 有关。他提出了一个非常好的记录器包装器。我将在下面粘贴他的代码:

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 的实现的正确方法是什么

注意:此问题与 有关,但现在特定于 Serilog。

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

您应该创建如下内容:

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);
    }
}

Does that mean that every class that will log sth (so basically every), should have ILogger in its constructor?

据我从史蒂文斯的回答中了解到:是的,你应该这样做。

what is the best way to use it later in the code?

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

如果您不使用 DI 容器,即您使用 Pure DI,那么您可以这样做:

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

ILogger logging_adapter = new SerilogAdapter(log);

var myobject = new MyClass(other_dependencies_here, logging_adapter);