创建/修改记录器之后,更新静态类记录器实例的推荐方法

时间:2020-05-04 21:03:51

标签: serilog liblog

在我的应用程序中,在创建记录器之前已加载了一些类。在这些类中更新记录器实例的推荐方法是什么?我应该添加LoggerCreated事件吗? 我正在使用LibLog,Serilog和.NET Framework。

以下是问题的一个示例:

  public class MainClass
  {
    public static void MainTest()
    {
      string logFile = TestClass.GetLogConfgurationFile();
      Serilog.Log.Logger = new LoggerConfiguration().ReadFrom.AppSettings(filePath: logFile).CreateLogger();
      TestClass.TestLogger(); // <== The log WILL NOT contain the expected "Hello, World!"
    }
  }
  public static class TestClass
  {
    private static ILog _logger = LogProvider.GetCurrentClassLogger();
    public static string GetLogConfgurationFile()
    {
      return @"C:\Serilog Config.xml";
    }
    public static void TestLogger()
    {
      _logger.Debug("Hello, World!");
    }
  }

这是我建议的解决方案:

  public class TestClass
  {
    public static event Action LoggerCreated;
    public static void MainTest()
    {
      string logFile = TestClass.GetLogConfgurationFile();
      Serilog.Log.Logger = new LoggerConfiguration().ReadFrom.AppSettings(filePath: logFile).CreateLogger();
      Action handler = LoggerCreated;
      handler?.Invoke();
      TestClass.TestLogger(); // <== The log WILL contain the expected "Hello, World!"
    }
  }
  public static class TestClass
  {
    private static ILog _logger = LogProvider.GetCurrentClassLogger();
    static TestClass()
    {
      TestClass.LoggerCreated += () => _logger = LogProvider.GetCurrentClassLogger();
    }
    private static void TestClass_LoggerCreated()
    {
      _logger = LogProvider.GetCurrentClassLogger();
    }
    public static string GetLogConfgurationFile()
    {
      return @"C:\Serilog Config.xml";
    }
    public static void TestLogger()
    {
      _logger.Debug("Hello, World!");
    }
  }

0 个答案:

没有答案