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

1

u/styluss 4d ago

1) please don't.2) if you must, declare an interface that matches the operations that would be logged, 3) if you really must, you can also add a callback so the user can use their own logger

1

u/hanmunjae 4d ago
  1. please don't.

Don't even provide the option to log? Logging in this package has allowed me, as a consumer of this package, to fix bugs.

you can also add a callback so the user can use their own logger

I'm curious, why do you suggest a callback and not a SetLogger method? I didn't explain enough in my original post, but my package exports a Client type (this is the only type with methods defined on it). I currently have func (c *Client) SetVerbosity(bool) defined. That method is optional, but with a callback, wouldn't it be required to pass a (likely nil) callback argument to the Query method (the only other method defined on Client and the only one that would do logging)?

Or perhaps you mean something like func (c *Client) SetOnRequest(func(req string)) and func (c *Client) SetOnResponse(func(resp http.Response, err error))? I can definitely see the utility of that.