github.com/erda-project/erda-infra@v1.0.9/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 "github.com/sirupsen/logrus" 19 20 "github.com/erda-project/erda-infra/base/logs" 21 ) 22 23 // Logger . 24 type Logger struct { 25 name string 26 *logrus.Entry 27 } 28 29 // New . 30 func New(options ...Option) logs.Logger { 31 log := logrus.New() 32 log.SetFormatter(&logrus.TextFormatter{ 33 ForceColors: true, 34 FullTimestamp: true, 35 TimestampFormat: "2006-01-02 15:04:05.000", 36 }) 37 logger := &Logger{"", logrus.NewEntry(log)} 38 for _, opt := range options { 39 processOptions(log, logger, opt.get()) 40 } 41 return logger 42 } 43 44 // Sub . 45 func (l *Logger) Sub(name string) logs.Logger { 46 if len(l.name) > 0 { 47 name = l.name + "." + name 48 } 49 return &Logger{name, l.Entry.WithField("module", name)} 50 } 51 52 // SetLevel . 53 func (l *Logger) SetLevel(lvl string) error { 54 level, err := logrus.ParseLevel(lvl) 55 if err != nil { 56 return err 57 } 58 l.Logger.SetLevel(level) 59 return nil 60 } 61 62 func processOptions(logr *logrus.Logger, logger *Logger, opt interface{}) { 63 switch val := opt.(type) { 64 case setNameOption: 65 logger.name = string(val) 66 case logrus.Level: 67 logr.SetLevel(val) 68 } 69 } 70 71 // Option . 72 type Option interface { 73 get() interface{} 74 } 75 76 type option struct{ value interface{} } 77 78 func (o *option) get() interface{} { return o.value } 79 80 type setNameOption string 81 82 // WithName . 83 func WithName(name string) Option { 84 return &option{setNameOption(name)} 85 } 86 87 // WithLevel . 88 func WithLevel(level logrus.Level) Option { 89 return &option{level} 90 }