Document concurrent use criteria & improve unit test.
Chris Hines
8 years ago
10 | 10 |
}
|
11 | 11 |
|
12 | 12 |
// NewLogfmtLogger returns a logger that encodes keyvals to the Writer in
|
13 | |
// logfmt format.
|
|
13 |
// logfmt format. The passed Writer must be safe for concurrent use by
|
|
14 |
// multiple goroutines if the returned Logger will be used concurrently.
|
14 | 15 |
func NewLogfmtLogger(w io.Writer) Logger {
|
15 | 16 |
return &logfmtLogger{w}
|
16 | 17 |
}
|
17 | 18 |
|
18 | 19 |
func (l logfmtLogger) Log(keyvals ...interface{}) error {
|
|
20 |
// The Logger interface requires implementations to be safe for concurrent
|
|
21 |
// use by multiple goroutines. For this implementation that means making
|
|
22 |
// only one call to l.w.Write() for each call to Log. We first collect all
|
|
23 |
// of the bytes into b, and then call l.w.Write(b).
|
19 | 24 |
b, err := logfmt.MarshalKeyvals(keyvals...)
|
20 | 25 |
if err != nil {
|
21 | 26 |
return err
|
6 | 6 |
"testing"
|
7 | 7 |
|
8 | 8 |
"github.com/go-kit/kit/log"
|
|
9 |
"gopkg.in/logfmt.v0"
|
9 | 10 |
)
|
10 | 11 |
|
11 | 12 |
func TestLogfmtLogger(t *testing.T) {
|
|
31 | 32 |
if err := logger.Log("std_map", map[int]int{1: 2}, "my_map", mymap{0: 0}); err != nil {
|
32 | 33 |
t.Fatal(err)
|
33 | 34 |
}
|
34 | |
if want, have := "std_map=\"unsupported value type\" my_map=special_behavior\n", buf.String(); want != have {
|
|
35 |
if want, have := "std_map=\""+logfmt.ErrUnsupportedValueType.Error()+"\" my_map=special_behavior\n", buf.String(); want != have {
|
35 | 36 |
t.Errorf("want %#v, have %#v", want, have)
|
36 | 37 |
}
|
37 | 38 |
}
|