Last active
July 4, 2017 08:23
-
-
Save tusing/0232e33f668383f6c64b831ec999b5dc to your computer and use it in GitHub Desktop.
Go logging boilerplate
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"flag" | |
"github.com/op/go-logging" | |
"os" | |
) | |
func makeLogger(name string, minLevel logging.Level) logging.Logger { | |
log := logging.MustGetLogger(name) | |
format := logging.MustStringFormatter( | |
`%{color}%{time:15:04:05.000} %{shortfunc} ▶ %{level:.4s} %{id:03x}%{color:reset} %{message}`, | |
) | |
logBackend := logging.NewLogBackend(os.Stderr, "", 0) | |
logFormattedBackend := logging.NewBackendFormatter(logBackend, format) | |
logLeveledBackend := logging.AddModuleLevel(logFormattedBackend) | |
logLeveledBackend.SetLevel(minLevel, "") | |
logging.SetBackend(logLeveledBackend) | |
return *log | |
} | |
func parseLogLevel(arg string) logging.Level { | |
levels := map[string]logging.Level{ | |
"info": logging.INFO, | |
"notice": logging.NOTICE, | |
"warning": logging.WARNING, | |
"error": logging.ERROR, | |
"critical": logging.CRITICAL, | |
} | |
return levels[arg] | |
} | |
var log logging.Logger | |
func main() { | |
logLevel := flag.String("level", "error", | |
`Log level: <info|notice|warning|error|critical>`) | |
flag.Parse() | |
log = makeLogger("loggerName", parseLogLevel(*logLevel)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment