Backend plugins: Log wrapper args formatting (#20514)

Backend plugins is recommended to use hclog with json 
formatting to get proper log output in grafana server log.
Old hclog-wrapper.go that I deleted while back is still in 
the repo so deletes that.
This commit is contained in:
Marcus Efraimsson
2019-11-20 14:27:28 +01:00
committed by GitHub
parent ec18e2bfc3
commit 58b7958952
5 changed files with 58 additions and 63 deletions

View File

@ -13,20 +13,41 @@ type logWrapper struct {
Logger glog.Logger
}
func formatArgs(args ...interface{}) []interface{} {
if len(args) == 0 || len(args)%2 != 0 {
return args
}
res := []interface{}{}
for n := 0; n < len(args); n = n + 2 {
key := args[n]
if stringKey, ok := key.(string); ok && stringKey == "timestamp" {
continue
}
res = append(res, key)
res = append(res, args[n+1])
}
return res
}
func (lw logWrapper) Trace(msg string, args ...interface{}) {
lw.Logger.Debug(msg, args...)
lw.Logger.Debug(msg, formatArgs(args...)...)
}
func (lw logWrapper) Debug(msg string, args ...interface{}) {
lw.Logger.Debug(msg, args...)
lw.Logger.Debug(msg, formatArgs(args...)...)
}
func (lw logWrapper) Info(msg string, args ...interface{}) {
lw.Logger.Info(msg, args...)
lw.Logger.Info(msg, formatArgs(args...)...)
}
func (lw logWrapper) Warn(msg string, args ...interface{}) {
lw.Logger.Warn(msg, args...)
lw.Logger.Warn(msg, formatArgs(args...)...)
}
func (lw logWrapper) Error(msg string, args ...interface{}) {
lw.Logger.Error(msg, args...)
lw.Logger.Error(msg, formatArgs(args...)...)
}
func (lw logWrapper) IsTrace() bool { return true }

View File

@ -0,0 +1,29 @@
package backendplugin
import (
"fmt"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestLogWrapper(t *testing.T) {
tcs := []struct {
args []interface{}
expectedResult []interface{}
}{
{args: []interface{}{}, expectedResult: []interface{}{}},
{args: []interface{}{"1", "2", "3"}, expectedResult: []interface{}{"1", "2", "3"}},
{args: []interface{}{"1", "2"}, expectedResult: []interface{}{"1", "2"}},
{args: []interface{}{"1", "2", "timestamp", time.Now()}, expectedResult: []interface{}{"1", "2"}},
{args: []interface{}{"1", "2", "timestamp", time.Now(), "3", "4"}, expectedResult: []interface{}{"1", "2", "3", "4"}},
}
for i, tc := range tcs {
t.Run(fmt.Sprintf("formatArgs testcase %d", i), func(t *testing.T) {
res := formatArgs(tc.args...)
assert.Exactly(t, tc.expectedResult, res)
})
}
}