Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add StringifyLogger to eliminate "unsupported value type" #120

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions log/stringify_logger.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package log

import "fmt"

// StringifyLogger stringifies every value to make it printable by logfmt.
//
// Example:
// Logger := log.LogfmtLogger(os.Stderr)
// Logger = log.StringifyLogger{Logger}
type StringifyLogger struct {
Logger
}

func (l StringifyLogger) Log(keyvals ...interface{}) error {
for i := 1; i < len(keyvals); i += 2 {
switch keyvals[i].(type) {
case string, fmt.Stringer, fmt.Formatter:
case error:
default:
keyvals[i] = StringWrap{Value: keyvals[i]}
}
}
return l.Logger.Log(keyvals...)
}

var _ = fmt.Stringer(StringWrap{})

// StringWrap wraps the Value as a fmt.Stringer.
type StringWrap struct {
Value interface{}
}

// String returns a string representation (%v) of the underlying Value.
func (sw StringWrap) String() string {
return fmt.Sprintf("%v", sw.Value)
}
38 changes: 38 additions & 0 deletions log/stringify_logger_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package log_test

import (
"bytes"
"errors"
"testing"

"github.com/go-kit/kit/log"
)

func TestStringifyLogger(t *testing.T) {
buf := &bytes.Buffer{}
logger := log.NewLogfmtLogger(buf)
logger = log.StringifyLogger{logger}

if err := logger.Log("hello", "world"); err != nil {
t.Fatal(err)
}
if want, have := "hello=world\n", buf.String(); want != have {
t.Errorf("want %#v, have %#v", want, have)
}

buf.Reset()
if err := logger.Log("a", 1, "err", errors.New("error")); err != nil {
t.Fatal(err)
}
if want, have := "a=1 err=error\n", buf.String(); want != have {
t.Errorf("want %#v, have %#v", want, have)
}

buf.Reset()
if err := logger.Log("std_map", map[int]int{1: 2}, "my_map", mymap{0: 0}); err != nil {
t.Fatal(err)
}
if want, have := "std_map=map[1:2] my_map=special_behavior\n", buf.String(); want != have {
t.Errorf("want %#v, have %#v", want, have)
}
}