github.com/banzaicloud/operator-tools@v0.28.10/pkg/utils/log.go (about) 1 // Copyright © 2020 Banzai Cloud 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 utils 16 17 import ( 18 "fmt" 19 "io" 20 "os" 21 22 "emperror.dev/errors" 23 "github.com/go-logr/logr" 24 "github.com/spf13/cast" 25 ) 26 27 var GlobalLogLevel = 0 28 29 var Log = NewLogger("", os.Stderr, os.Stderr, 0) 30 31 func NewLogger(name string, out, err io.Writer, level int) logr.Logger { 32 sink := &logSink{ 33 name: name, 34 values: make([]interface{}, 0), 35 out: out, 36 err: err, 37 } 38 return logr.New(sink).V(level) 39 } 40 41 func joinAndSeparatePairs(values []interface{}) string { 42 joined := "" 43 for i, v := range values { 44 joined += cast.ToString(v) 45 if i%2 == 0 { 46 joined += ": " 47 } else { 48 if i < len(values)-1 { 49 joined += ", " 50 } 51 } 52 } 53 return joined 54 } 55 56 func getDetailedErr(err error) string { 57 details := errors.GetDetails(err) 58 if len(details) == 0 { 59 return err.Error() 60 } 61 return fmt.Sprintf("%s (%s)", err.Error(), joinAndSeparatePairs(details)) 62 } 63 64 type logSink struct { 65 name string 66 values []interface{} 67 out io.Writer 68 err io.Writer 69 } 70 71 func (s logSink) Init(logr.RuntimeInfo) {} 72 73 func (s logSink) Enabled(level int) bool { 74 return GlobalLogLevel >= level 75 } 76 77 func (s logSink) Info(level int, msg string, keysAndValues ...interface{}) { 78 if !s.Enabled(level) { 79 return 80 } 81 s.values = append(s.values, keysAndValues...) 82 if len(s.values) == 0 { 83 _, _ = fmt.Fprintf(s.out, "%s> %s\n", s.name, msg) 84 } else { 85 _, _ = fmt.Fprintf(s.out, "%s> %s %s\n", s.name, msg, joinAndSeparatePairs(s.values)) 86 } 87 } 88 89 func (s logSink) Error(err error, msg string, keysAndValues ...interface{}) { 90 s.values = append(s.values, keysAndValues...) 91 if len(s.values) == 0 { 92 _, _ = fmt.Fprintf(s.err, "%s> %s %s\n", s.name, msg, getDetailedErr(err)) 93 } else { 94 _, _ = fmt.Fprintf(s.err, "%s> %s %s %s\n", s.name, msg, getDetailedErr(err), joinAndSeparatePairs(s.values)) 95 } 96 } 97 98 func (s logSink) WithValues(keysAndValues ...interface{}) logr.LogSink { 99 l := len(s.values) 100 s.values = append(s.values[:l:l], keysAndValues...) 101 return s 102 } 103 104 func (s logSink) WithName(name string) logr.LogSink { 105 s.name += name 106 return s 107 }