aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorFelix Hanley <felix@userspace.com.au>2017-12-08 02:39:56 +0000
committerFelix Hanley <felix@userspace.com.au>2017-12-08 02:39:56 +0000
commita6d5e43da92cc7a6f404e501e2bd7bdd8d6be029 (patch)
treeb9375ae3495346166f4ec7ccbc7b9fb82e1bb997
parent82cda804becab8ffea6b287f471e77feccad63df (diff)
downloadlogger-a6d5e43da92cc7a6f404e501e2bd7bdd8d6be029.tar.gz
logger-a6d5e43da92cc7a6f404e501e2bd7bdd8d6be029.tar.bz2
Fix WithFields
-rw-r--r--level.go18
-rw-r--r--log.go4
-rw-r--r--outputs/keyvalue/keyvalue_test.go44
3 files changed, 66 insertions, 0 deletions
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)
+ }
+ }
+}