github.com/artisanhe/tools@v1.0.1-0.20210607022958-19a8fef2eb04/log/log.go (about) 1 package log 2 3 import ( 4 "io/ioutil" 5 "os" 6 "strings" 7 8 "github.com/sirupsen/logrus" 9 10 "github.com/artisanhe/tools/conf" 11 "github.com/artisanhe/tools/log/context" 12 "github.com/artisanhe/tools/log/hooks" 13 ) 14 15 type Log struct { 16 Name string 17 Path string 18 Level string `conf:"env"` 19 Format string 20 init bool 21 } 22 23 func (log Log) DockerDefaults() conf.DockerDefaults { 24 return conf.DockerDefaults{ 25 "Format": "json", 26 } 27 } 28 29 func (log Log) MarshalDefaults(v interface{}) { 30 if l, ok := v.(*Log); ok { 31 if l.Name == "" { 32 l.Name = os.Getenv("PROJECT_NAME") 33 } 34 35 if l.Level == "" { 36 l.Level = "DEBUG" 37 } 38 39 if l.Format == "" { 40 l.Format = "text" 41 } 42 } 43 } 44 45 func (log *Log) Init() { 46 if !log.init { 47 log.Create() 48 log.init = true 49 } 50 } 51 52 func (log *Log) Create() { 53 logrus.SetOutput(os.Stdout) 54 logrus.SetLevel(getLogLevel(log.Level)) 55 if log.Format == "json" { 56 logrus.SetFormatter(&logrus.JSONFormatter{}) 57 } else { 58 logrus.SetFormatter(&logrus.TextFormatter{ 59 ForceColors: true, 60 }) 61 } 62 logrus.AddHook(context.NewLogIDHook()) 63 64 logrus.AddHook(hooks.NewCallStackHook()) 65 logrus.AddHook(hooks.NewProjectHook(log.Name)) 66 67 logrus.SetOutput(ioutil.Discard) 68 69 if log.Path != "" { 70 logrus.AddHook(hooks.NewLogWriterHook(log.Path)) 71 logrus.AddHook(hooks.NewLogWriterForErrorHook(log.Path)) 72 } else { 73 logrus.AddHook(hooks.NewLogPrinterHook()) 74 logrus.AddHook(hooks.NewLogPrinterForErrorHook()) 75 } 76 77 } 78 79 func getLogLevel(l string) logrus.Level { 80 level, err := logrus.ParseLevel(strings.ToLower(l)) 81 if err == nil { 82 return level 83 } 84 return logrus.InfoLevel 85 }