github.com/johnnyeven/libtools@v0.0.0-20191126065708-61829c1adf46/log/hooks/log_printer.go (about) 1 package hooks 2 3 import ( 4 "os" 5 "sync" 6 7 "github.com/sirupsen/logrus" 8 ) 9 10 func NewLogPrinterHook() *LogPrinterHook { 11 return &LogPrinterHook{ 12 lock: new(sync.Mutex), 13 writer: os.Stdout, 14 levels: []logrus.Level{ 15 logrus.DebugLevel, 16 logrus.InfoLevel, 17 }, 18 } 19 } 20 21 func NewLogPrinterForErrorHook() *LogPrinterHook { 22 return &LogPrinterHook{ 23 lock: new(sync.Mutex), 24 writer: os.Stderr, 25 levels: []logrus.Level{ 26 logrus.WarnLevel, 27 logrus.ErrorLevel, 28 logrus.FatalLevel, 29 logrus.PanicLevel, 30 }, 31 } 32 } 33 34 type LogPrinterHook struct { 35 levels []logrus.Level 36 lock *sync.Mutex 37 writer *os.File 38 } 39 40 func (hook *LogPrinterHook) Fire(entry *logrus.Entry) error { 41 hook.lock.Lock() 42 defer hook.lock.Unlock() 43 44 msg, err := entry.String() 45 if err != nil { 46 return err 47 } else { 48 hook.writer.Write([]byte(msg)) 49 } 50 51 return nil 52 } 53 54 func (hook *LogPrinterHook) Levels() []logrus.Level { 55 return hook.levels 56 }