github.com/gitbundle/modules@v0.0.0-20231025071548-85b91c5c3b01/log/logrus.go (about) 1 // Copyright 2023 The GitBundle Inc. All rights reserved. 2 // Copyright 2017 The Gitea Authors. All rights reserved. 3 // Use of this source code is governed by a MIT-style 4 // license that can be found in the LICENSE file. 5 6 package log 7 8 import ( 9 "fmt" 10 "os" 11 "sort" 12 "strings" 13 "sync" 14 ) 15 16 var entry = &Entry{ 17 Data: map[string]interface{}{}, 18 pool: &sync.Pool{}, 19 } 20 21 type Fields map[string]interface{} 22 23 type Entry struct { 24 Data map[string]interface{} 25 pool *sync.Pool 26 } 27 28 func NewEntry() *Entry { 29 return entry 30 } 31 32 func (e *Entry) newEntry() *Entry { 33 entry, ok := e.pool.Get().(*Entry) 34 if ok { 35 return entry 36 } 37 return &Entry{Data: map[string]interface{}{}, pool: e.pool} 38 } 39 40 func (e *Entry) releaseEntry(entry *Entry) { 41 e.Data = map[string]interface{}{} 42 e.pool.Put(entry) 43 } 44 45 func (e *Entry) WithFields(fields Fields) *Entry { 46 data := make(Fields, len(e.Data)+len(fields)) 47 for k, v := range e.Data { 48 data[k] = v 49 } 50 for k, v := range fields { 51 data[k] = v 52 } 53 return &Entry{Data: data, pool: e.pool} 54 } 55 56 func (e *Entry) WithField(key string, value interface{}) *Entry { 57 entry := e.newEntry() 58 defer e.releaseEntry(entry) 59 return entry.WithFields(Fields{key: value}) 60 } 61 62 func (e *Entry) WithError(err error) *Entry { 63 entry := e.newEntry() 64 defer e.releaseEntry(entry) 65 return entry.WithField("error", err) 66 } 67 68 func (e *Entry) log(level Level, format string, v ...interface{}) { 69 elems := make([]string, 0, 8) 70 for k, v := range e.Data { 71 elems = append(elems, fmt.Sprintf("%s=%v", k, v)) 72 } 73 sort.Strings(elems) 74 v = append(v, strings.Join(elems, "\t")) 75 Log(2, level, format+" %s", v...) 76 } 77 78 func (e *Entry) Trace(format string, v ...interface{}) { 79 e.log(TRACE, format, v...) 80 } 81 82 func (e *Entry) Debug(format string, v ...interface{}) { 83 e.log(DEBUG, format, v...) 84 } 85 86 func (e *Entry) Info(format string, v ...interface{}) { 87 e.log(INFO, format, v...) 88 } 89 90 func (e *Entry) Warn(format string, v ...interface{}) { 91 e.log(WARN, format, v...) 92 } 93 94 func (e *Entry) Error(format string, v ...interface{}) { 95 e.log(ERROR, format, v...) 96 } 97 98 func (e *Entry) Critical(format string, v ...interface{}) { 99 e.log(CRITICAL, format, v...) 100 } 101 102 func (e *Entry) Fatal(format string, v ...interface{}) { 103 e.log(FATAL, format, v...) 104 Close() 105 os.Exit(1) 106 } 107 108 func WithField(key string, value interface{}) *Entry { 109 return entry.WithField(key, value) 110 } 111 112 func WithFields(fields Fields) *Entry { 113 return entry.WithFields(fields) 114 } 115 116 func WithError(err error) *Entry { 117 return entry.WithError(err) 118 }