From 6c17eaa62f2e6c18bdb323a008bb5c61dd62a2b5 Mon Sep 17 00:00:00 2001 From: Brian Picciano Date: Wed, 18 Jul 2018 23:01:28 +0000 Subject: [PATCH] mlog: implement KVerFunc and Prefix --- mlog/mlog.go | 21 +++++++++++++++++++++ mlog/mlog_test.go | 12 ++++++++++++ 2 files changed, 33 insertions(+) diff --git a/mlog/mlog.go b/mlog/mlog.go index 5d6250b..da0ab79 100644 --- a/mlog/mlog.go +++ b/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 { diff --git a/mlog/mlog_test.go b/mlog/mlog_test.go index 152a010..b4072e8 100644 --- a/mlog/mlog_test.go +++ b/mlog/mlog_test.go @@ -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"}), + )) +}