Should you add logging to common libraries that are used in many applications? For example, if I have a parser that’s used in multiple apps, should I add logging inside the parser? My concern is that it couples all users to the logging framework.
I’m particularly interested in solutions for shared libraries that are used outside of the implementer’s organization. For instance, would Microsoft add logging into any of the base class libraries? Why or why not? What options are there for troubleshooting if you leave out logging?
3
If coupling users to the logging framework is an issue, you may use:
-
Either Dependency Injection to make the consumers of the shared library provide the library with the logging feature.
Of course, this means that either there is a common logger interface which is standardized enough, such as PSR-3 for PHP, or you are able to provide an interface generic enough to make it possible to create adapters for different logging frameworks.
-
The pros of this approach is that you don’t need to handle different logging frameworks yourself: you may provide an implementation for your logging interface for your preferred logging framework, and let consumers create their own adapters for other logging frameworks.
-
The cons is that designing a good interface which will be easy to use with any logging framework may not be an easy task. Using a standard (PSR-3 being an example) as a foundation can be helpful.
-
-
Or use application configuration to determine which one of the logging frameworks should be used.
This requires to have a standard for configuration files: some languages/frameworks do have one, such as .NET Framework (app.config/web.config files). Unfortunately, others do not (such as node.js).
-
The pros is that consumers don’t have to do anything special to make your library work for them. If they don’t need logging, they don’t configure anything. If they need logging, they select a logging framework among the supported ones and configure it in the same standard way they would do for their own application.
-
The cons is that while you may provide support for mainstream logging frameworks, one day you’ll have to accommodate your library for a new framework. Also, providing support for multiple frameworks may make your library grow in size and increase the number of dependencies, unless you use plugins which are usually difficult to implement.
-