Search code examples
c#inversion-of-controllog4netautofacserilog

How to use Autofac with a Serilog wrapper class


A while ago we started to replace our logger from log4net to Serilog in order to send our logs straight to our Elastic. In our project we are working with IOC using Autofac. As so, we initially created a wrapper class (LogSerilog) and a corresponding interface (ILogSerilog) which we added to our builder, when in the class LogSerilog we configured the root logger.

public class LogSerilog : ILogSerilog
{
    private readonly IElasticConfiguration configuration;
    public LogSerilog(IElasticConfiguration configuration)
    {
        this.configuration = configuration;
        Init();
    }
    public void Init()
    {
        var logger = new LoggerConfiguration().MinimumLevel.Information().Enrich.WithMachineName();
        try
        {
            logger.WriteTo.Elasticsearch(
                this.configuration.GetElasticPath(), typeName: "Serilog");
        }
        catch (Exception)
        {
            //Swallow - Elastic is N/A don't wan't to crash. logging won't help since I don't have logger yet :)
        }
        logger.WriteTo.Log4Net();
        Log.Logger = logger.CreateLogger();
    }
    ..........

After that I saw the autofac-serilog-integration Nuget which seem like the best solution for me.because it will wire all the context for us. The problem is that it seem it doesn't work.Even more, the log4net sink (we are still using log4net to have a copy of the logs in the machine) doesn't work as well! I feel like I'm doing some thing wrong here - but I'm not sure how should I fix it.

  1. If I will remove the wrrapper class, where should I config the root logger?
  2. Is the problem with the log4net sink has nothing to do with the wrapper class?
  3. Any other tip if you see I'm approaching it in the wrong way would be welcomed.

Solution

  • After some investigation, I found the answers to my questions.

    1. If I will remove the wrrapper class, where should I config the root logger?
      In the main class - just when the program starts to run\ Before I need to log for the first time.
    2. Is the problem with the log4net sink has nothing to do with the wrapper class?
      No, it had to do with a reference to an old log4net dll version
    3. Any other tip if you see I'm approaching it in the wrong way would be welcomed.
      There is not really a problem to have a Serilog wrapper - it wasn't the problem - but I do find it problematic because for example the Autofac Serilog integration doesn't support it and you need to give the context by your own.