本文介绍了Serilog 的 ILogger 使用 Log.ForContext<T> 注入,其中 T 是消费者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Serilog 允许创建上下文感知记录器:

Serilog allows creating a context-aware logger:

Log.ForContext()

我想以 T 是使用者的类型,即它被注入到哪个类中的方式向 SimpleInjector 注册 Serilog.

I would like to register Serilog with SimpleInjector in such a way that T is the type of the consumer, i.e. it is which class it is injected in to.

例如

public class Car
{
    public Car(ILogger logger) <= would be injected using Log.ForContext<Car>()
    {
    }
}

我可以看到这个已经用 AutoFac 完成了.

查看SimpleInjector 文档,有一个非常有前景的重载RegisterConditional()(带有 Func 参数).

And looking through the SimpleInjector documentation, there is a very promising overload of RegisterConditional() (with the Func<TypeFactoryContext, Type> parameter).

c.RegisterConditional(typeof (ILogger),
    x => Log.ForContext(x.Consumer.ImplementationType), <= won't compile as expecting a Type
    Lifestyle.Scoped,
    x => true);

然而,我不想告诉 SimpleInjector 哪个类型要构建,而是如何构建一个.

however, I don't want to tell SimpleInjector which Type to build, but how to build one.

推荐答案

我根据 StackOverflow 上的@Steven 天才回答,将 Serilog 与 Simple Injector 集成了以下代码:记录器包装器最佳实践

I have integrated Serilog with Simple Injector with the following code based on @Steven genius answer on StackOverflow: logger wrapper best practice

public interface ILogger
{
    void Log(LogEntry entry);
}

public class SerilogLogger<T> : ILogger
{
    private readonly Serilog.ILogger _logger;

    public SerilogLogger()
    {
        _logger = new LoggerConfiguration()
            .WriteTo
            .Trace(LogEventLevel.Information)
            .CreateLogger()
            .ForContext(typeof (T));
    }

    public void Log(LogEntry entry)
    {
        /* Logging abstraction handling */
    }
}

public static class ContainerExtensions {

    public static void RegisterLogging(this Container container)
    {
        container.RegisterConditional(
            typeof(ILogger),
            c => typeof(SerilogLogger<>).MakeGenericType(c.Consumer.ImplementationType),
            Lifestyle.Singleton,
            c => true);
    }

}

在您的组合根中:

var container = new Container();
container.RegisterLogging();

这篇关于Serilog 的 ILogger 使用 Log.ForContext<T> 注入,其中 T 是消费者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-29 01:02
查看更多