This solution is built on top of Go's log/slog
package and leverages slog.Default()
. To use it a developer should declare a package variable logger
in every package that is part of their Go project that needs to perform logging (e.g. a package containing only type
, var
and/or const
declarations would usually not need a logger.go
file.)
Add a logger.go
file to every packages and then add this line to the file, updating it with the package's name:
var logger = logging.NewPackageLogger("<package_name>")
This uses a small logging
package you can find below which has a Logger
type simply to embed slog.Log
. This allows adding extra methods beyond that provided by slog.Logger
and to preprocess calls to *slog.Logger
if we later find that to be needed.
Now, I do not love this approach because it introduces a package-scoped variable into every package, but it is the most apparently workable solution I have tried to date, this being about my 5th iteration of trying to find a workable solution for logging.
BTW, sure would be nice if the Go team would add a way for the compiler to capture the name of the current package using a well-known constant like PACKAGE_NAME
or similar, but I digress.
At the time of this posting (2025-03) this code has not yet been run in production so it may turn out to be unworkable. If you are reading this and have reason to believe it is unworkable please do help me and anyone else who might read this by elaborating in depth as any issues you can see with this approach.