How can we make prints in the library more controllable? That is, how can the consumer manage logging?
sobes.tech AI
Answer from AI
To make output (prints) in a library more controllable and to give the consumer the ability to manage logging, the following approaches are usually used:
-
Using a logging interface: Instead of directly calling
fmt.Printlnorlog.Print, the library accepts or sets a logger that implements a specific interface (for example, with methodsInfo(),Error(),Debug()). -
Supporting logging levels: Allows enabling or disabling output of messages of different importance (debug, info, warn, error).
-
Using standard logging packages: For example,
log.Loggerfrom the standard library or third-party packages (zap, logrus), which can be configured externally. -
Passing context or logging configuration: Allows dynamically changing logging behavior.
Example:
// Logger interface
type Logger interface {
Info(msg string)
Error(msg string)
}
// In the library
var logger Logger = defaultLogger // defaultLogger implements Logger
func SetLogger(l Logger) {
logger = l
}
func DoSomething() {
logger.Info("Starting work")
// ...
}
The library user can pass their own logger with the desired level of detail and output format.