@ The answer to CedmundoMartinez fluttered my head to come up with (very simple and pretty obvious, now that I can use the rearview mirrors).
I am posting my answer here for those interested in a similar solution.
What I did was make a copy of the standard log package (src / log / log.go) and expand it. It could not be easier to get a global logger that already does everything that a standard logger does, and all you want! In this case, record alignment is supported.
The only changes I had to make:
type Logger struct { mu sync.Mutex // ensures atomic writes; protects the following fields prefix string // prefix to write at beginning of each line flag int // properties out io.Writer // destination for output buf []byte // for accumulating text to write level int // One of DEBUG, ERROR, INFO }
Only the last line is added. The log package sets the global variable std , which can then be used to access string fields from any function in the package.
Then I added constants for different levels of the log:
const ( DEBUG = 1 << iota INFO ERROR )
Next, I added my functions:
(Note: ct is a package https://github.com/seago/go-colortext that allows console color text on windows, so all errors here are printed in red)
func Error(v ...interface{}) { if std.level <= ERROR { ct.ChangeColor(ct.Red, true, ct.None, false) s := fmt.Sprintf("ERROR: %v", v...) std.Output(2, s) ct.ResetColor() } } func Info(format string, v ...interface{}) { if std.level <= INFO { s := fmt.Sprintf("INFO: "+format, v...) std.Output(2, s) } } func Debug(v ...interface{}) { if std.level <= DEBUG { s := fmt.Sprintf("DEBUG: %v", v...) std.Output(2, s) } } func SetLogLevel(lvl int) { std.level = lvl }
And this! With this, I can now use it by simply importing the modified package instead of the standard log package and open it:
import ( "errors" "tryme/log" ) func main() { log.SetLogLevel(log.INFO) log.Info("This is a test Info") err := errors.New("This is a test error!!!") log.Error(err) log.Debug("Testing debugging")
This, of course, is just a demo version, and it can be easily expanded with more log levels, output formatting, etc.
You can use all the functions that the standard log package provides, for example, SetOutput for writing to a file or MultiWriter for writing to a file and console, etc.