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>
This commit is contained in:
Sofia Papagiannaki
2022-06-23 13:24:26 +02:00
committed by GitHub
co-authored by Emil Tullstedt
parent 1f49296f8f
commit 84e2e1ec8e
2 changed files with 43 additions and 3 deletions
+39
View File
@@ -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
}