123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 |
- // short for "log"
- package lg
- import (
- "fmt"
- "log"
- "os"
- "strings"
- )
- const (
- DEBUG = LogLevel(1)
- INFO = LogLevel(2)
- WARN = LogLevel(3)
- ERROR = LogLevel(4)
- FATAL = LogLevel(5)
- )
- type AppLogFunc func(lvl LogLevel, f string, args ...interface{})
- type Logger interface {
- Output(maxdepth int, s string) error
- }
- type NilLogger struct{}
- func (l NilLogger) Output(maxdepth int, s string) error {
- return nil
- }
- type LogLevel int
- func (l *LogLevel) Get() interface{} { return *l }
- func (l *LogLevel) Set(s string) error {
- lvl, err := ParseLogLevel(s)
- if err != nil {
- return err
- }
- *l = lvl
- return nil
- }
- func (l *LogLevel) String() string {
- switch *l {
- case DEBUG:
- return "DEBUG"
- case INFO:
- return "INFO"
- case WARN:
- return "WARNING"
- case ERROR:
- return "ERROR"
- case FATAL:
- return "FATAL"
- }
- return "invalid"
- }
- func ParseLogLevel(levelstr string) (LogLevel, error) {
- switch strings.ToLower(levelstr) {
- case "debug":
- return DEBUG, nil
- case "info":
- return INFO, nil
- case "warn":
- return WARN, nil
- case "error":
- return ERROR, nil
- case "fatal":
- return FATAL, nil
- }
- return 0, fmt.Errorf("invalid log level '%s' (debug, info, warn, error, fatal)", levelstr)
- }
- func Logf(logger Logger, cfgLevel LogLevel, msgLevel LogLevel, f string, args ...interface{}) {
- if cfgLevel > msgLevel {
- return
- }
- logger.Output(3, fmt.Sprintf(msgLevel.String()+": "+f, args...))
- }
- func LogFatal(prefix string, f string, args ...interface{}) {
- logger := log.New(os.Stderr, prefix, log.Ldate|log.Ltime|log.Lmicroseconds)
- Logf(logger, FATAL, FATAL, f, args...)
- os.Exit(1)
- }
|