Which pattern to use for logging? Dependency Injection or Service Locator?

后端 未结 9 947
别那么骄傲
别那么骄傲 2021-01-31 15:51

Consider this scenario. I have some business logic that now and then will be required to write to a log.

interface ILogger
{
    void Log(string stuff);
}

inte         


        
相关标签:
9条回答
  • 2021-01-31 16:09

    My little rule of thumb:

    • If it's in a class library, use either constructor injection or property injection with a null-object pattern.

    • If it's in a main application, use the service locator (or singleton).

    I find this applies pretty well when using log4net. You don't want class libraries reaching out to things that might not be there, but in an application program, you know that the logger is going to be there, and libraries like log4net are based heavily around the service-location pattern.

    I tend to think of logging as something sufficiently static that it doesn't really need DI. It's extremely unlikely that I'll ever change the logging implementation in an application, especially since every logging framework out there is incredibly flexible and easy to extend. It's more important in class libraries when your library might need to be used by several applications which already use different loggers.

    YMMV, of course. DI is great but that doesn't mean everything needs to be DI'ed.

    0 讨论(0)
  • 2021-01-31 16:19

    Maybe this will be little offtopic, but why do we need injecting logger at all, when we can just type at the beggining of the class:

    Logger logger = LogManager.GetLogger("MyClassName");
    

    Logger doesn't change during development and later during maintenance. Modern loggers are highly customizable, so argument

    what if I want to replace text logger with database?

    is missed.

    I don't negate using dependency injection, I'm just curious about your mind.

    0 讨论(0)
  • 2021-01-31 16:19

    I'd recommend neither of these approaches. Better to use aspect-oriented programming. Logging is the "hello world" of AOP.

    0 讨论(0)
提交回复
热议问题