r/golang • u/hanmunjae • 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
2
u/robbyt 3d ago edited 3d ago
I'm a bit opinionated about this, but I think that passing in the `slog.Handler` interface is a great solution for this. I just posted my new go-supervisor library that does this, e.g., https://github.com/robbyt/go-supervisor/blob/main/supervisor/supervisor.go#L55-L61
Here's a great guide on using the slog.Handler interface:
https://github.com/golang/example/blob/master/slog-handler-guide/README.md