Should I take ILogger, ILogger, ILoggerFactory or ILoggerProvider for a library?

后端 未结 8 1468
不知归路
不知归路 2020-12-04 06:59

This may be somewhat related to Pass ILogger or ILoggerFactory to constructors in AspNet Core?, however this is specifically about Library Design, not about

8条回答
  •  -上瘾入骨i
    2020-12-04 07:53

    For library design good approach would be:

    1.Do not force consumers to inject logger to your classes. Simply create another ctor passing NullLoggerFactory.

    class MyClass
    {
        private readonly ILoggerFactory _loggerFactory;
    
        public MyClass():this(NullLoggerFactory.Instance)
        {
    
        }
        public MyClass(ILoggerFactory loggerFactory)
        {
          this._loggerFactory = loggerFactory ?? NullLoggerFactory.Instance;
        }
    }
    

    2. Limit number of categories which you use when you create loggers to allow consumers configure logs filtering easily. this._loggerFactory.CreateLogger(Consts.CategoryName)

提交回复
热议问题