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

后端 未结 8 1485
不知归路
不知归路 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条回答
  •  盖世英雄少女心
    2020-12-04 07:35

    Sticking to the question, I believe ILogger is the right option, considering downside of other options:

    1. Injecting ILoggerFactory force your user to give away the control of the mutable global logger factory to your class library. Moreover, by accepting ILoggerFactory your class now can write to log with any arbitrary category name with CreateLogger method. While ILoggerFactory is usually available as a singleton in DI container, I as a user would doubt why any library would need to use it.
    2. While the method ILoggerProvider.CreateLogger looks like it, it is not intended for injection. It is used with ILoggerFactory.AddProvider so the factory can create aggregated ILogger that writes to multiple ILogger created from each registered providers. This is clear when you inspect the implementation of LoggerFactory.CreateLogger
    3. Accepting ILogger also looks like the way to go, but it is impossible with .NET Core DI. This actually sounds like the reason why they needed to provide ILogger at the first place.

    So after all, we have no better choice than ILogger, if we were to choose from those classes.

    Another approach would be to inject something else that wraps non-generic ILogger, which in this case should be non-generic one. The idea is that by wrapping it with your own class, you take full control of how user could configure it.

提交回复
热议问题