mlog: implement KVerFunc and Prefix
This commit is contained in:
parent
0a4be2f8cd
commit
6c17eaa62f
21
mlog/mlog.go
21
mlog/mlog.go
@ -104,6 +104,14 @@ type KVer interface {
|
||||
KV() KV
|
||||
}
|
||||
|
||||
// KVerFunc is a function which implements the KVer interface by calling itself.
|
||||
type KVerFunc func() KV
|
||||
|
||||
// KV implements the KVer interface by calling the KVerFunc itself.
|
||||
func (kvf KVerFunc) KV() KV {
|
||||
return kvf()
|
||||
}
|
||||
|
||||
// KV is a set of key/value pairs which provides context for a log entry by a
|
||||
// KVer. KV is itself also a KVer.
|
||||
type KV map[string]interface{}
|
||||
@ -170,6 +178,19 @@ func MergeInto(kv KVer, kvs ...KVer) KVer {
|
||||
return mergeInto(kv, kvs...)
|
||||
}
|
||||
|
||||
// Prefix prefixes the all keys returned from the given KVer with the given
|
||||
// prefix string.
|
||||
func Prefix(kv KVer, prefix string) KVer {
|
||||
return KVerFunc(func() KV {
|
||||
kvv := kv.KV()
|
||||
newKVV := make(KV, len(kvv))
|
||||
for k, v := range kvv {
|
||||
newKVV[prefix+k] = v
|
||||
}
|
||||
return newKVV
|
||||
})
|
||||
}
|
||||
|
||||
// Message describes a message to be logged, after having already resolved the
|
||||
// KVer
|
||||
type Message struct {
|
||||
|
@ -9,6 +9,7 @@ import (
|
||||
. "testing"
|
||||
"time"
|
||||
|
||||
"github.com/mediocregopher/mediocre-go-lib/mtest/massert"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
@ -142,3 +143,14 @@ func TestMerge(t *T) {
|
||||
KV{"a": "a"}, KV{"a": "b"},
|
||||
)
|
||||
}
|
||||
|
||||
func TestPrefix(t *T) {
|
||||
kv := KV{"foo": "bar"}
|
||||
prefixKV := Prefix(kv, "aa")
|
||||
|
||||
massert.Fatal(t, massert.All(
|
||||
massert.Equal(kv.KV(), KV{"foo": "bar"}),
|
||||
massert.Equal(prefixKV.KV(), KV{"aafoo": "bar"}),
|
||||
massert.Equal(kv.KV(), KV{"foo": "bar"}),
|
||||
))
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user