Serilog's ILogger injected using Log.ForContext, where T is the consumer

后端 未结 1 745
天命终不由人
天命终不由人 2021-02-03 10:17

Serilog allows creating a context-aware logger:

Log.ForContext()

I would like to register Serilog with SimpleInjector in such a way that

1条回答
  •  孤街浪徒
    2021-02-03 10:44

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

    In your Composition Root:

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

    0 讨论(0)
提交回复
热议问题