Sobes.tech
Senior

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:

  1. Using a logging interface: Instead of directly calling fmt.Println or log.Print, the library accepts or sets a logger that implements a specific interface (for example, with methods Info(), Error(), Debug()).

  2. Supporting logging levels: Allows enabling or disabling output of messages of different importance (debug, info, warn, error).

  3. Using standard logging packages: For example, log.Logger from the standard library or third-party packages (zap, logrus), which can be configured externally.

  4. 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.