接上节内容,我们继续讲解日志的其他部分.

ILoggerProvider以及扩展类

我们在上节的架构图上并没有看到有直接实现该接口的实现类。那么如果将Logger类直接使用会有什么结果呢?

var factory = new LoggerFactory();
var logger = factory.CreateLogger("name");
logger.Log(LogLevel.Debug, 0, "state", null, null);

这段代码能够正常运行但是不会记录任何日志。因为Logger类并没有直接记录日志的功能,需要通过LoggerFactory的GetProviders方法创建能够直接工作的ILogger类型日志。所以即使现在的工程中没有对于ILoggerProvider的扩展,但是我们可以预测:Microsoft.Framework.Logging.Console、Microsoft.Framework.Logging.NLog、Microsoft.Framework.Logging.TraceSource都会对ILoggerProvider进行实现,当然由于ILoggerProvider会产生ILogger,所以他们也会实现ILogger类。
ILogValues以及扩展

我们看到日志记录类的接口为:Log(LogLevel logLevel, int eventId, object state, Exception exception, Func<object, Exception, string> formatter)

该接口通过formatter将state和exception组合成字符串对象,然后记录到log中。如果使用扩展方法系统传入的formatter永远是:MessageFormatter

        private static string MessageFormatter(object state, Exception error)
        {
            if (state == null && error == null)
            {
                throw new InvalidOperationException("No message or exception details were found " +
                    "to create a message for the log.");
            }

            if (state == null)
            {
                return error.ToString();
            }

            if (error == null)
            {
                return state.ToString();
            }

            return string.Format(CultureInfo.CurrentCulture, "{0}{1}{2}", state, Environment.NewLine, error);
        }
MessageFormatter

相关文章:

  • 2021-11-01
  • 2022-12-23
  • 2021-07-06
  • 2022-03-06
  • 2021-10-05
  • 2022-03-03
  • 2022-02-06
  • 2021-12-14
猜你喜欢
  • 2022-02-28
  • 2021-07-11
  • 2021-10-27
  • 2021-09-25
  • 2021-09-08
  • 2022-12-23
相关资源
相似解决方案