Logging globally (across packages)
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.
I'm posting the solution worked for me!. I just created my own package, and I used the init function.
package logging
import (
"io"
logging "log"
"os"
"github.com/Sirupsen/logrus"
)
var (
log *logrus.Logger
)
func init() {
f, err := os.OpenFile("logs/application.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
logging.Fatalf("error opening file: %v", err)
}
log = logrus.New()
//log.Formatter = &logrus.JSONFormatter{}
log.SetReportCaller(true)
mw := io.MultiWriter(os.Stdout, f)
log.SetOutput(mw)
}
// Info ...
func Info(format string, v ...interface{}) {
log.Infof(format, v...)
}
// Warn ...
func Warn(format string, v ...interface{}) {
log.Warnf(format, v...)
}
// Error ...
func Error(format string, v ...interface{}) {
log.Errorf(format, v...)
}
var (
// ConfigError ...
ConfigError = "%v type=config.error"
// HTTPError ...
HTTPError = "%v type=http.error"
// HTTPWarn ...
HTTPWarn = "%v type=http.warn"
// HTTPInfo ...
HTTPInfo = "%v type=http.info"
)
And on any package, just import my package and I execute the (Info, Warn, Error) function
package main
import (
log "logging"
)
func main() {
log.Error(log.ConfigError, "Testing the error")
}
The log entry will be saved rendered on the screen and it will be saved on a file.