Skip to content

Instantly share code, notes, and snippets.

@ccpaging
Last active May 19, 2022 08:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ccpaging/a804b916d93e561cbd1a309fe231e4ab to your computer and use it in GitHub Desktop.
Save ccpaging/a804b916d93e561cbd1a309fe231e4ab to your computer and use it in GitHub Desktop.
Simple Multi-level logger based on go standard log library
package main
import (
"fmt"
"log"
)
var (
Ldebug = "DEBG "
Linfo = "INFO "
)
type Logger interface {
// Info is equivalent to Print() and logs the message at level Info.
Info(v ...any)
// Infof is equivalent to Printf() and logs the message at level Info.
Infof(format string, v ...any)
// Infoln is equivalent to Println() and logs the message at level Info.
Infoln(v ...any)
// Debug is equivalent to Print() and logs the message at level Debug.
Debug(v ...any)
// Debugf is equivalent to Printf() and logs the message at level Debug.
Debugf(format string, v ...any)
// Debugln is equivalent to Println() and logs the message at level Debug.
Debugln(v ...any)
}
type Outputter interface {
Output(calldepth int, s string) error
}
type MultiLogger map[string]Outputter
func (ml MultiLogger) Add(key string, l Outputter) MultiLogger {
ml[key] = l
return ml
}
func (ml MultiLogger) Remove(key string) {
delete(ml, key)
}
func (ml MultiLogger) Debug(v ...interface{}) {
if l, ok := ml[Ldebug]; ok {
l.Output(2, Ldebug+fmt.Sprint(v...))
}
}
func (ml MultiLogger) Debugf(format string, v ...interface{}) {
if l, ok := ml[Ldebug]; ok {
l.Output(2, Ldebug+fmt.Sprintf(format, v...))
}
}
func (ml MultiLogger) Debugln(v ...interface{}) {
if l, ok := ml[Ldebug]; ok {
l.Output(2, Ldebug+fmt.Sprintln(v...))
}
}
func (ml MultiLogger) Info(v ...interface{}) {
if l, ok := ml[Linfo]; ok {
l.Output(2, Linfo+fmt.Sprint(v...))
}
}
func (ml MultiLogger) Infof(format string, v ...interface{}) {
if l, ok := ml[Linfo]; ok {
l.Output(2, Linfo+fmt.Sprintf(format, v...))
}
}
func (ml MultiLogger) Infoln(v ...interface{}) {
if l, ok := ml[Linfo]; ok {
l.Output(2, Linfo+fmt.Sprintln(v...))
}
}
func main() {
l := log.Default()
ml := make(MultiLogger)
ml.Add(Ldebug, l)
ml.Add(Linfo, l)
ml.Debug("This is debug")
ml.Info("This is info")
// Output:
// 2021/11/23 23:57:01 DEBG This is debug
// 2021/11/23 23:57:01 INFO This is info
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment