【问题标题】:How to use Autofac with a Serilog wrapper class如何将 Autofac 与 Serilog 包装类一起使用
【发布时间】:2018-10-09 22:53:48
【问题描述】:

不久前,我们开始将我们的记录器从 log4net 替换为 Serilog,以便将我们的日志直接发送到我们的 Elastic。在我们的项目中,我们正在使用IOC 使用Autofac。因此,我们最初创建了一个包装类 (LogSerilog) 和一个相应的接口 (ILogSerilog),我们将它们添加到我们的构建器中,而在类 LogSerilog 中我们配置了 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();
    }
    ..........

在那之后,我看到了autofac-serilog-integration Nuget,这对我来说似乎是最好的解决方案。因为它会为我们连接所有上下文。问题是它似乎不起作用。甚至,log4net sink(我们仍然使用log4net在机器中拥有日志的副本)也无法正常工作!我觉得我在这里做错了什么 - 但我不确定我应该如何解决它。

  1. 如果我要删除包装类,我应该在哪里配置根记录器?
  2. log4net sink 的问题与包装类无关吗?
  3. 欢迎任何其他提示,如果您发现我以错误的方式接近它。

【问题讨论】:

    标签: c# inversion-of-control log4net autofac serilog


    【解决方案1】:

    Serilog 有一个方便的静态类,用于设置和保留日志配置。 这是我环境中常见配置的示例:

    string SerilogPrefix = "SerilogPrefix";
    
    Log.Logger = new LoggerConfiguration()
        .ReadFrom.AppSettings(settingPrefix: SerilogPrefix) 
        .Enrich.FromLogContext()
        .Enrich.WithMemoryUsage()
        .Enrich.WithProcessId()
        .Enrich.WithThreadId()
        .Enrich.WithExceptionDetails()
        .Enrich.With(new LogEnricher())        // optional custom class to add properties to the log message
        .Filter.With(new SerilogEventFilter()) // optional custom class to filter messages
        .CreateLogger();
    

    在 nuget 上查看这些包:

    Serilog.Settings.AppSettings
    Serilog.Enrichers.Memory
    Serilog.Enrichers.Process
    Serilog.Enrichers.Thread
    Serilog.Sinks.Seq
    SerilogMetrics
    

    【讨论】:

    • 感谢提示,但是它如何回答我的问题?
    【解决方案2】:

    经过一番调查,我找到了问题的答案。

    1. 如果我要删除 wrapper 类,我应该在哪里配置根记录器?
      在主类中 - 就在程序开始运行时\在我需要第一次登录之前时间
    2. log4net sink 的问题与包装类无关吗?
      不,它与对旧 log4net dll 版本的引用有关
    3. 如果您发现我以错误的方式接近它,任何其他提示都将受到欢迎
      拥有 Serilog 包装器并不是真正的问题 - 这不是问题- 但我确实发现它有问题,因为例如 Autofac Serilog integration 不支持它,您需要自己提供上下文

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-22
      • 2021-12-17
      • 1970-01-01
      • 2023-01-12
      • 1970-01-01
      • 1970-01-01
      • 2022-06-25
      • 1970-01-01
      相关资源
      最近更新 更多