2019-06-18 21:02:11 +00:00
|
|
|
package logger
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"io/ioutil"
|
|
|
|
"os"
|
|
|
|
"sync"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
type defaultLogger struct {
|
|
|
|
logLevel LogLevel
|
|
|
|
mutex *sync.Mutex
|
|
|
|
stdout io.Writer
|
|
|
|
stderr io.Writer
|
|
|
|
}
|
|
|
|
|
|
|
|
func (dl *defaultLogger) Debug(f string, v ...interface{}) {
|
|
|
|
dl.log(LogLevelDebug, f, v...)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (dl *defaultLogger) Info(f string, v ...interface{}) {
|
|
|
|
dl.log(LogLevelInfo, f, v...)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (dl *defaultLogger) Warn(f string, v ...interface{}) {
|
|
|
|
dl.log(LogLevelWarn, f, v...)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (dl *defaultLogger) Error(f string, v ...interface{}) {
|
|
|
|
dl.log(LogLevelError, f, v...)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (dl *defaultLogger) Fatal(f string, v ...interface{}) {
|
|
|
|
dl.log(LogLevelFatal, f, v...)
|
|
|
|
os.Exit(1)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (dl *defaultLogger) log(ll LogLevel, f string, v ...interface{}) {
|
2019-06-24 15:13:42 +00:00
|
|
|
|
|
|
|
if dl.logLevel > ll {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2019-06-18 21:02:11 +00:00
|
|
|
layout := "2006/01/02 15:04:05"
|
|
|
|
dw := dl.stdout
|
2019-06-24 15:13:42 +00:00
|
|
|
prefix := ""
|
|
|
|
switch ll {
|
|
|
|
case LogLevelDebug:
|
|
|
|
prefix = "DEBUG"
|
|
|
|
case LogLevelInfo:
|
|
|
|
prefix = "INFO"
|
|
|
|
case LogLevelWarn:
|
|
|
|
prefix = "WARN"
|
2019-06-18 21:02:11 +00:00
|
|
|
case LogLevelError:
|
2019-06-24 15:13:42 +00:00
|
|
|
prefix = "ERROR"
|
2019-06-18 21:02:11 +00:00
|
|
|
dw = dl.stderr
|
|
|
|
case LogLevelFatal:
|
2019-06-24 15:13:42 +00:00
|
|
|
prefix = "FATAL"
|
2019-06-18 21:02:11 +00:00
|
|
|
dw = dl.stderr
|
|
|
|
}
|
|
|
|
dl.mutex.Lock()
|
2019-06-24 15:13:42 +00:00
|
|
|
fmt.Fprintf(dw, "%v %v: %v\n", time.Now().Format(layout), prefix, fmt.Sprintf(f, v...))
|
2019-06-18 21:02:11 +00:00
|
|
|
dl.mutex.Unlock()
|
|
|
|
}
|
|
|
|
|
2019-06-24 15:13:42 +00:00
|
|
|
func NewDefaultLogger(logLevel LogLevel) Logger {
|
2019-06-18 21:02:11 +00:00
|
|
|
return &defaultLogger{
|
|
|
|
logLevel: logLevel,
|
|
|
|
mutex: new(sync.Mutex),
|
|
|
|
stdout: os.Stdout,
|
|
|
|
stderr: os.Stderr,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-06-24 15:13:42 +00:00
|
|
|
func NewCustomLogger(loglevel LogLevel, out io.Writer, err io.Writer) Logger {
|
|
|
|
return &defaultLogger{
|
|
|
|
logLevel: loglevel,
|
|
|
|
mutex: new(sync.Mutex),
|
|
|
|
stdout: out,
|
|
|
|
stderr: err,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewSilentLogger() Logger {
|
2019-06-18 21:02:11 +00:00
|
|
|
return &defaultLogger{
|
|
|
|
logLevel: LogLevelDebug,
|
|
|
|
mutex: new(sync.Mutex),
|
|
|
|
stdout: ioutil.Discard,
|
|
|
|
stderr: ioutil.Discard,
|
|
|
|
}
|
|
|
|
}
|