I am working on building a API and SDK for a web service. My question is what is the correct practice for logging. Should the SDK do logging for the API methods? All the SDKs I have seen do not do this so I am just wondering is that the recommended best practice?
If you don't write code directly for end users but for other developers, I would generally not make assumptions about the needs of these developers unless you have to. Whenever you have the choice, leave the final choice to the people that will later on use your code.
If there are meaningful messages that can be logged in your SDK, log output may help to debug problems and discover issues. Thus I would implement a logging facility that allows the users of your code to provide an own log function/object/callback, so they can control if something is logged at all, where it is logged, and how it is logged. That way the users can also easily combine your log messages with their own logging facilities and collect all application logs in a central place or skip logging altogether by discarding all log messages.
A dependency which sole purpose is to offers special behavior that other classes use because of business logic (or use cases) should not contain a use case inside of itself. What?
Your SDK is a
tool for others to use during their use case. Whatever is relevant "logged" information will depend on the Use Case. Your SDK doesn't know and cannot pretend to know the answer to some very important questions:
- What level of logging do we want to use at any given moment? (Trace, Debug, Info, Warning, Error, Fatal)
- What should be included in the logs that are relevant for any given use case vs another? Date? What format? Stack trace? Error Message? What about localizing error messages?
SDKs, and any other
know-how abstraction** should throw exceptions when it
fails, or receive a callback function for error handling. And maybe, depending on how far you want to take it, you could return errors, warnings, info messages or codes in whatever your methods return so that the user of the SDK can decide what it wants to do with it.
** know-how abstractions: DB client/driver, ORM client, HTTP client, even clients that you build within your company/team, service classes, any piece of code that knows how to do something but doesn't decide when or why that happens.
Leave logging up to the application.
Logging in an SDK ties you to a particular logging framework. There have been many attempts to "standardize" logging in various languages, but few, if any, have achieved universal adoption. Using any of them will be an annoyance (or worse) to the developer of any application that uses a different one, or none at all.
Leaving logging up to the application will also help you write a better SDK. Too often, useful information is just logged instead of being exposed in the API.