github.com/sealerio/sealer@v0.11.1-0.20240507115618-f4f89c5853ae/pkg/logger/formatter.go (about) 1 // Copyright © 2022 Alibaba Group Holding Ltd. 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 logger 16 17 import ( 18 "bytes" 19 "fmt" 20 "path/filepath" 21 "strings" 22 23 "github.com/sirupsen/logrus" 24 ) 25 26 const ( 27 colorRed = 31 28 colorYellow = 33 29 colorBlue = 36 30 colorGray = 37 31 ) 32 33 const ( 34 defaultTimestampFormat = "2006-01-02 15:04:05" 35 ) 36 37 func getColorByLevel(level logrus.Level) int { 38 switch level { 39 case logrus.DebugLevel, logrus.TraceLevel: 40 return colorGray 41 case logrus.WarnLevel: 42 return colorYellow 43 case logrus.ErrorLevel, logrus.FatalLevel, logrus.PanicLevel: 44 return colorRed 45 default: 46 return colorBlue 47 } 48 } 49 50 type Formatter struct { 51 // DisableColor disable colors 52 DisableColor bool 53 // HideLogTime if send to remote log system that already adds timestamps. 54 HideLogTime bool 55 // HideLogPath more simple log message without file and lines 56 HideLogPath bool 57 TimestampFormat string 58 } 59 60 func (f *Formatter) Format(entry *logrus.Entry) ([]byte, error) { 61 var b *bytes.Buffer 62 if entry.Buffer != nil { 63 b = entry.Buffer 64 } else { 65 b = &bytes.Buffer{} 66 } 67 68 timestampFormat := f.TimestampFormat 69 if timestampFormat == "" { 70 timestampFormat = defaultTimestampFormat 71 } 72 73 if !f.HideLogTime { 74 b.WriteString(entry.Time.Format(timestampFormat)) 75 } 76 77 levelStr := strings.ToUpper(entry.Level.String()) 78 79 newLog := fmt.Sprintf(" [%s] %s\n", levelStr, entry.Message) 80 81 if !f.HideLogPath { 82 if entry.HasCaller() { 83 fName := filepath.Base(entry.Caller.File) 84 newLog = fmt.Sprintf(" [%s] [%s:%d] %s\n", levelStr, fName, entry.Caller.Line, entry.Message) 85 } 86 } 87 88 if !f.DisableColor { 89 levelColor := getColorByLevel(entry.Level) 90 //here is the console color format specification example: 91 //var Reset = "\033[0m" 92 //var Red = "\033[31m" 93 //var Green = "\033[32m" 94 //var Yellow = "\033[33m" 95 //var Blue = "\033[34m" 96 //var Purple = "\033[35m" 97 //var Cyan = "\033[36m" 98 //var Gray = "\033[37m" 99 //var White = "\033[97m" 100 101 fmt.Fprintf(b, "\033[%dm%s\033[0m", levelColor, newLog) 102 } else { 103 b.WriteString(newLog) 104 } 105 106 b.WriteByte('\n') 107 108 return b.Bytes(), nil 109 }