From a6d5e43da92cc7a6f404e501e2bd7bdd8d6be029 Mon Sep 17 00:00:00 2001 From: Felix Hanley Date: Fri, 8 Dec 2017 13:39:56 +1100 Subject: Fix WithFields --- level.go | 18 ++++++++++++++++ log.go | 4 ++++ outputs/keyvalue/keyvalue_test.go | 44 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 66 insertions(+) diff --git a/level.go b/level.go index 3d2aee4..73fa57d 100644 --- a/level.go +++ b/level.go @@ -1,5 +1,7 @@ package logger +import "strings" + // Level defines the logger output level type Level int @@ -30,3 +32,19 @@ func (lvl Level) String() string { return "unknown" } } + +// LevelFromString helps select a level +func LevelFromString(l string) Level { + switch strings.ToLower(l) { + case "debug": + return Debug + case "warn": + return Warn + case "Info": + return Info + case "Error": + return Error + default: + return NoLevel + } +} diff --git a/log.go b/log.go index 84587dc..3afcbcd 100644 --- a/log.go +++ b/log.go @@ -65,6 +65,9 @@ func (l logger) Log(lvl Level, args ...interface{}) { l.lock.Lock() defer l.lock.Unlock() + // Place fields at the end + args = append(args, l.fields...) + msg := Message{ Name: l.name, Time: ts.Format(l.timeFormat), @@ -72,6 +75,7 @@ func (l logger) Log(lvl Level, args ...interface{}) { Fields: make([]interface{}, 0), } + // Allow for map arguments for _, f := range args { switch c := f.(type) { case map[string]string: diff --git a/outputs/keyvalue/keyvalue_test.go b/outputs/keyvalue/keyvalue_test.go index b45a5cd..bf02879 100644 --- a/outputs/keyvalue/keyvalue_test.go +++ b/outputs/keyvalue/keyvalue_test.go @@ -51,3 +51,47 @@ func TestKeyValueWriter(t *testing.T) { } } } + +func TestKeyValueWriterWithFields(t *testing.T) { + var tests = []struct { + in []interface{} + out string + }{ + { + in: []interface{}{"one"}, + out: "[INFO ] test: message=one added=this\n", + }, + { + in: []interface{}{"one", "two", "2"}, + out: "[INFO ] test: message=one two=2 added=this\n", + }, + { + in: []interface{}{"one", "two", "2", "three", 3}, + out: "[INFO ] test: message=one two=2 three=3 added=this\n", + }, + { + in: []interface{}{"one", "two", "2", "three", 3, "fo ur", "# 4"}, + out: "[INFO ] test: message=one two=2 three=3 \"fo ur\"=\"# 4\" added=this\n", + }, + } + for _, tt := range tests { + var buf bytes.Buffer + logger := logger.New(&logger.Options{ + Name: "test", + Output: &buf, + Formatter: New(), + }).WithFields("added", "this") + + logger.Info(tt.in...) + + str := buf.String() + + // Chop timestamp + dataIdx := strings.IndexByte(str, ' ') + rest := str[dataIdx+1:] + + if rest != tt.out { + t.Errorf("Info(%q) => %q, expected %q\n", tt.in, rest, tt.out) + } + } +} -- cgit v1.2.3