github.com/whiteboxio/flow@v0.0.3-0.20190918184116-508d75d68a2c/pkg/corev1alpha1/logger.go (about) 1 package corev1alpha1 2 3 import ( 4 "fmt" 5 "io" 6 "os" 7 "time" 8 ) 9 10 type LogSev uint8 11 12 const ( 13 LogSevDebug LogSev = iota 14 LogSevTrace 15 LogSevInfo 16 LogSevWarn 17 LogSevError 18 LogSevFatal 19 ) 20 21 type Log struct { 22 sev LogSev 23 payload string 24 } 25 26 func NewLog(sev LogSev, payload string) *Log { 27 return &Log{ 28 sev: sev, 29 payload: payload, 30 } 31 } 32 33 type Logger struct { 34 logs chan *Log 35 out io.Writer 36 done chan struct{} 37 } 38 39 var _ Runner = (*Logger)(nil) 40 41 func NewLogger(out io.Writer) *Logger { 42 return &Logger{ 43 logs: make(chan *Log), 44 out: out, 45 done: make(chan struct{}), 46 } 47 } 48 49 func (logger *Logger) Start() error { 50 go func() { 51 var err error 52 for log := range logger.logs { 53 _, err = fmt.Fprintln(logger.out, logger.Format(log)) 54 if err != nil { 55 panic(err.Error()) 56 } 57 } 58 close(logger.done) 59 }() 60 61 return nil 62 } 63 64 func (logger *Logger) Stop() error { 65 close(logger.logs) 66 <-logger.done 67 68 return nil 69 } 70 71 var LogSevLex map[LogSev]string 72 73 func init() { 74 LogSevLex = map[LogSev]string{ 75 LogSevDebug: "DEBUG", 76 LogSevTrace: "TRACE", 77 LogSevInfo: "INFO", 78 LogSevWarn: "WARN", 79 LogSevError: "ERROR", 80 LogSevFatal: "FATAL", 81 } 82 } 83 84 func (logger *Logger) Format(log *Log) string { 85 return fmt.Sprintf( 86 "%s\t%s\t%s", 87 time.Now().Format(time.RFC3339), 88 LogSevLex[log.sev], 89 log.payload, 90 ) 91 } 92 93 func (logger *Logger) Debug(format string, a ...interface{}) { 94 logger.logs <- NewLog(LogSevDebug, fmt.Sprintf(format, a...)) 95 } 96 97 func (logger *Logger) Trace(format string, a ...interface{}) { 98 logger.logs <- NewLog(LogSevTrace, fmt.Sprintf(format, a...)) 99 } 100 101 func (logger *Logger) Info(format string, a ...interface{}) { 102 logger.logs <- NewLog(LogSevInfo, fmt.Sprintf(format, a...)) 103 } 104 105 func (logger *Logger) Warn(format string, a ...interface{}) { 106 logger.logs <- NewLog(LogSevWarn, fmt.Sprintf(format, a...)) 107 } 108 109 func (logger *Logger) Error(format string, a ...interface{}) { 110 logger.logs <- NewLog(LogSevError, fmt.Sprintf(format, a...)) 111 } 112 113 func (logger *Logger) Fatal(format string, a ...interface{}) { 114 logger.logs <- NewLog(LogSevFatal, fmt.Sprintf(format, a...)) 115 logger.Stop() 116 logger.terminate() 117 } 118 119 func (logger *Logger) terminate() { 120 os.Exit(1) 121 }