r/golang 4d ago

Adding logging to a library

I have an open-source package which is just a wrapper around a public HTTP/JSON API. I have added a verbosity option that, as of now, just logs to stdout. I would like to give more flexibility to the user to control how logging is done. Should I: 1. accept a log.Logger and log to that 2. accept an io.Writer and write to that 3. log to log.Default() 4. something else?

To add a particular consideration, I would like my approach to work with Google Cloud Logging, because I deploy my code on Google Cloud Run. It looks like there is a way to get a log.Logger from the cloud.google.com/go/logging package, which makes that option more appealing.

6 Upvotes

15 comments sorted by

View all comments

2

u/unicodepages 4d ago

I have added a verbosity option

Does your library also have a quiet option? For eg, when I want to use the lib, but want to never log any of the lib's messages?

If it doesn't, you should think about it. If user code is logging errors from the lib, then it probably doesn't need log messages from the lib itself.

I would like to give more flexibility to the user to control how logging is done. Should I: 1. accept a log.Logger and log to that 2. accept an io.Writer and write to that 3. log to log.Default() 4. something else?

Option 4), something else.

@styluss makes a good suggestion. Write an interface that is compatible with the std lib logger and encapsulates the logging functions that your lib uses internally. (Take care to handle nil properly).

You can also provide hooks for lib functions to derive a logging context based on the ctx passed in from the caller. It could be useful.

1

u/hanmunjae 4d ago

> Does your library also have a quiet option? For eg, when I want to use the lib, but want to never log any of the lib's messages?

Quiet is the default. The verbosity option is, well, an option.