mirror of https://github.com/grafana/grafana
Log: Fix text logging for unsupported types (#51306)
* Fix text log for unsupported types * Apply suggestions from code review Co-authored-by: Emil Tullstedt <emil.tullstedt@grafana.com>pull/51318/head
parent
1f49296f8f
commit
84e2e1ec8e
@ -0,0 +1,39 @@ |
||||
package text |
||||
|
||||
import ( |
||||
"encoding" |
||||
"fmt" |
||||
"io" |
||||
"reflect" |
||||
|
||||
gokitlog "github.com/go-kit/kit/log" |
||||
) |
||||
|
||||
type textLogger struct { |
||||
w io.Writer |
||||
} |
||||
|
||||
// NewTextLogger similar to gokitlog.NewLogfmtLogger
|
||||
// but converts unsupported types to string
|
||||
func NewTextLogger(w io.Writer) gokitlog.Logger { |
||||
return &textLogger{w} |
||||
} |
||||
|
||||
func (l textLogger) Log(keyvals ...interface{}) error { |
||||
for i, val := range keyvals { |
||||
switch val.(type) { |
||||
case nil, string, []byte, encoding.TextMarshaler, error, fmt.Stringer: // supported natively by gokit.
|
||||
default: |
||||
switch reflect.TypeOf(val).Kind() { |
||||
case reflect.Array, reflect.Chan, reflect.Func, reflect.Map, reflect.Slice, reflect.Struct: |
||||
keyvals[i] = fmt.Sprintf("%+v", val) |
||||
default: |
||||
} |
||||
} |
||||
} |
||||
ll := gokitlog.NewLogfmtLogger(l.w) |
||||
if err := ll.Log(keyvals...); err != nil { |
||||
return err |
||||
} |
||||
return nil |
||||
} |
Loading…
Reference in new issue