Assigning loggers to package-level variables is an anti-pattern. When you declare var log = mylogger.New()
in the package namespace, you create a tight compile-time dependency on the particular brand of logger you use. It makes your program brittle, hard to change.
The solution is to pass an interface that describes the capabilities of a compatible logger but ignores its identity until runtime. But what does that look like? Specifically, what does it look like when you want to pass a logger to a function whose signature is not under your control?
The http.HandlerFunc
is a type where logging is essential but unintuitive:
type HandlerFunc(ResponseWriter, *Request)
Confronted with this signature, a package-level logger that you can access from inside the HandlerFunc
seems like an easy solution, but it’ll come back to bite you as your program evolves. Our mission: to inject a logging interface into something that looks and behaves like the mighty HandlerFunc
.
#go #coding #software-development #golang #programming