mirror of https://github.com/sirupsen/logrus.git
Merge pull request #34 from shuhaowu/chained-with-fields
Added support to chain withfields
This commit is contained in:
commit
9186db83c2
13
entry.go
13
entry.go
|
@ -38,15 +38,18 @@ func (entry *Entry) String() (string, error) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func (entry *Entry) WithField(key string, value interface{}) *Entry {
|
func (entry *Entry) WithField(key string, value interface{}) *Entry {
|
||||||
entry.Data[key] = value
|
return entry.WithFields(Fields{key: value})
|
||||||
return entry
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (entry *Entry) WithFields(fields Fields) *Entry {
|
func (entry *Entry) WithFields(fields Fields) *Entry {
|
||||||
for key, value := range fields {
|
data := Fields{}
|
||||||
entry.WithField(key, value)
|
for k, v := range entry.Data {
|
||||||
|
data[k] = v
|
||||||
}
|
}
|
||||||
return entry
|
for k, v := range fields {
|
||||||
|
data[k] = v
|
||||||
|
}
|
||||||
|
return &Entry{Logger: entry.Logger, Data: data}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (entry *Entry) log(level string, levelInt Level, msg string) string {
|
func (entry *Entry) log(level string, levelInt Level, msg string) string {
|
||||||
|
|
|
@ -98,3 +98,33 @@ func TestInfoShouldNotAddSpacesBetweenStrings(t *testing.T) {
|
||||||
assert.Equal(t, fields["msg"], "testtest")
|
assert.Equal(t, fields["msg"], "testtest")
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestWithFieldsShouldAllowAssignments(t *testing.T) {
|
||||||
|
var buffer bytes.Buffer
|
||||||
|
var fields Fields
|
||||||
|
|
||||||
|
logger := New()
|
||||||
|
logger.Out = &buffer
|
||||||
|
logger.Formatter = new(JSONFormatter)
|
||||||
|
|
||||||
|
localLog := logger.WithFields(Fields{
|
||||||
|
"key1": "value1",
|
||||||
|
})
|
||||||
|
|
||||||
|
localLog.WithField("key2", "value2").Info("test")
|
||||||
|
err := json.Unmarshal(buffer.Bytes(), &fields)
|
||||||
|
assert.Nil(t, err)
|
||||||
|
|
||||||
|
assert.Equal(t, "value2", fields["key2"])
|
||||||
|
assert.Equal(t, "value1", fields["key1"])
|
||||||
|
|
||||||
|
buffer = bytes.Buffer{}
|
||||||
|
fields = Fields{}
|
||||||
|
localLog.Info("test")
|
||||||
|
err = json.Unmarshal(buffer.Bytes(), &fields)
|
||||||
|
assert.Nil(t, err)
|
||||||
|
|
||||||
|
_, ok := fields["key2"]
|
||||||
|
assert.Equal(t, false, ok)
|
||||||
|
assert.Equal(t, "value1", fields["key1"])
|
||||||
|
}
|
||||||
|
|
Loading…
Reference in New Issue