I have spent a lot of time now searching and reading posts on the subject but have note yet managed to fully get my question answered - or perhaps I just need more clarification on existing answers.
I have read this post which has the same title as mine, but it's about logging across go routines rather than packages.
What I'm trying to solve is logging across the main app and any packages it uses. I need a logger that can log to multiple locations (which can be done with io.MultiWriter) and can do things like log.Error() and log.Debug()
I know there are packages that do this and I know how to implement those things myself.
What I can't get my head around is how to properly use it with my packages.
One way is of course to create the logger in main and then pass it around to all functions that need logging. But it seems awkward.
My ideal solution would be to have a logger like the built in global logger from the log package, but with the added functionality as above.
I mostly want this for optional debug logging within packages, so I can turn this on in a production version if needed.
What is the proper way to do this?
The proper way is what you think is the ideal way. Just create a package (preferably following Go's conventions https://golang.org/doc/code.html) and make your Log global:
package mylog
// Define your custom logger type.
type logger struct { /* Whatever you want */ }
// Optionally make it a interface.
type Logger interface { /* Your functions */ }
// And just go global.
var defaultLogger *Logger
func init(){
defaultLogger = new(logger)
}
func Debug(params ...string){
// Have some fun.
}
// ...
Also I would recommend to describe in documentation that your project uses that logging feature.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments