github.com/dkischenko/gomarkdoc@v0.0.0-20230516135336-e40deae8a495/logger/logger.go (about) 1 // Package logger provides a simple console logger for reporting information 2 // about execution to stderr. 3 package logger 4 5 import ( 6 "github.com/sirupsen/logrus" 7 prefixed "github.com/x-cray/logrus-prefixed-formatter" 8 ) 9 10 type ( 11 // Logger provides basic logging capabilities at different logging levels. 12 Logger interface { 13 Debug(a ...interface{}) 14 Debugf(format string, a ...interface{}) 15 Info(a ...interface{}) 16 Infof(format string, a ...interface{}) 17 Warn(a ...interface{}) 18 Warnf(format string, a ...interface{}) 19 Error(a ...interface{}) 20 Errorf(format string, a ...interface{}) 21 } 22 23 // Level defines valid logging levels for a Logger. 24 Level int 25 26 // Option defines an option for configuring the logger. 27 Option func(opts *options) 28 29 // options defines options for configuring the logger 30 options struct { 31 fields map[string]interface{} 32 } 33 ) 34 35 // Valid logging levels 36 const ( 37 DebugLevel Level = iota + 1 38 InfoLevel 39 WarnLevel 40 ErrorLevel 41 ) 42 43 // New initializes a new Logger. 44 func New(level Level, opts ...Option) Logger { 45 var options options 46 for _, opt := range opts { 47 opt(&options) 48 } 49 50 log := logrus.New() 51 52 formatter := &prefixed.TextFormatter{ 53 DisableTimestamp: true, 54 } 55 formatter.SetColorScheme(&prefixed.ColorScheme{ 56 DebugLevelStyle: "cyan", 57 PrefixStyle: "black+h", 58 }) 59 60 log.Formatter = formatter 61 62 switch level { 63 case DebugLevel: 64 log.SetLevel(logrus.DebugLevel) 65 case InfoLevel: 66 log.SetLevel(logrus.InfoLevel) 67 case WarnLevel: 68 log.SetLevel(logrus.WarnLevel) 69 case ErrorLevel: 70 log.SetLevel(logrus.ErrorLevel) 71 default: 72 log.SetLevel(logrus.ErrorLevel) 73 } 74 75 if options.fields != nil { 76 return log.WithFields(options.fields) 77 } 78 79 return log 80 } 81 82 // WithField sets the provided key/value pair for use on all logs. 83 func WithField(key string, value interface{}) Option { 84 return func(opts *options) { 85 if opts.fields == nil { 86 opts.fields = make(map[string]interface{}) 87 } 88 89 opts.fields[key] = value 90 } 91 }