github.com/erda-project/erda-infra@v1.0.10-0.20240327085753-f3a249292aeb/base/logs/logrusx/log.go (about) 1 // Copyright (c) 2021 Terminus, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package logrusx 16 17 import ( 18 "io" 19 20 "github.com/sirupsen/logrus" 21 22 "github.com/erda-project/erda-infra/base/logs" 23 ) 24 25 // Logger . 26 type Logger struct { 27 name string 28 *logrus.Entry 29 } 30 31 // New . 32 func New(options ...Option) logs.Logger { 33 log := logrus.New() 34 log.SetFormatter(&logrus.TextFormatter{ 35 ForceColors: true, 36 FullTimestamp: true, 37 TimestampFormat: "2006-01-02 15:04:05.000", 38 }) 39 logger := &Logger{"", logrus.NewEntry(log)} 40 for _, opt := range options { 41 processOptions(log, logger, opt.get()) 42 } 43 return logger 44 } 45 46 // Sub . 47 func (l *Logger) Sub(name string) logs.Logger { 48 if len(l.name) > 0 { 49 name = l.name + "." + name 50 } 51 return &Logger{name, l.Entry.WithField("module", name)} 52 } 53 54 // SetLevel . 55 func (l *Logger) SetLevel(lvl string) error { 56 level, err := logrus.ParseLevel(lvl) 57 if err != nil { 58 return err 59 } 60 l.Logger.SetLevel(level) 61 return nil 62 } 63 64 func (l *Logger) SetOutput(output io.Writer) { 65 l.Logger.SetOutput(output) 66 } 67 68 func processOptions(logr *logrus.Logger, logger *Logger, opt interface{}) { 69 switch val := opt.(type) { 70 case setNameOption: 71 logger.name = string(val) 72 case logrus.Level: 73 logr.SetLevel(val) 74 } 75 } 76 77 // Option . 78 type Option interface { 79 get() interface{} 80 } 81 82 type option struct{ value interface{} } 83 84 func (o *option) get() interface{} { return o.value } 85 86 type setNameOption string 87 88 // WithName . 89 func WithName(name string) Option { 90 return &option{setNameOption(name)} 91 } 92 93 // WithLevel . 94 func WithLevel(level logrus.Level) Option { 95 return &option{level} 96 }