71 lines
1.4 KiB
Go
71 lines
1.4 KiB
Go
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{}) {
|
|
layout := "2006/01/02 15:04:05"
|
|
dw := dl.stdout
|
|
switch dl.logLevel {
|
|
case LogLevelError:
|
|
dw = dl.stderr
|
|
case LogLevelFatal:
|
|
dw = dl.stderr
|
|
}
|
|
dl.mutex.Lock()
|
|
fmt.Fprintf(dw, "%v %v: %v \n", time.Now().Format(layout), ll, fmt.Sprintf(f, v...))
|
|
dl.mutex.Unlock()
|
|
}
|
|
|
|
func NewDefaultLogger(logLevel LogLevel, time bool) *defaultLogger {
|
|
return &defaultLogger{
|
|
logLevel: logLevel,
|
|
mutex: new(sync.Mutex),
|
|
stdout: os.Stdout,
|
|
stderr: os.Stderr,
|
|
}
|
|
}
|
|
|
|
func NewSilentLogger() *defaultLogger {
|
|
return &defaultLogger{
|
|
logLevel: LogLevelDebug,
|
|
mutex: new(sync.Mutex),
|
|
stdout: ioutil.Discard,
|
|
stderr: ioutil.Discard,
|
|
}
|
|
}
|