Skip to content

Commit d261fce

Browse files
authored
logctx.AddField(ctx, key, value) added (#7)
1 parent 54b0ba3 commit d261fce

File tree

3 files changed

+11
-2
lines changed

3 files changed

+11
-2
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ Small, easy to use, yet powerful utility packages for [**logrus**](https://githu
44

55
## `logctx` package [![GoDoc](https://godoc.org/github.com/go-logrusutil/logrusutil/logctx?status.svg)](https://godoc.org/github.com/go-logrusutil/logrusutil/logctx)
66

7-
Add a log entry to the context using `logctx.New(ctx, logEntry)`. Retrieve the log entry using `logctx.From(ctx)`.
7+
Add a log entry to the context using `logctx.New(ctx, logEntry)` or simply add a new log field using `logctx.AddField(ctx, key, value)`. Retrieve the log entry using `logctx.From(ctx)`.
88

99
## `errfield` package [![GoDoc](https://godoc.org/github.com/go-logrusutil/logrusutil/errfield?status.svg)](https://godoc.org/github.com/go-logrusutil/logrusutil/errfield)
1010

logctx/logctx.go

+6
Original file line numberDiff line numberDiff line change
@@ -25,3 +25,9 @@ func From(ctx context.Context) *logrus.Entry {
2525
}
2626
return Default
2727
}
28+
29+
// AddField adds a log field to the contexual log entry.
30+
func AddField(ctx context.Context, key string, value interface{}) context.Context {
31+
entry := From(ctx).WithField(key, value)
32+
return New(ctx, entry)
33+
}

logctx/logctx_test.go

+4-1
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,12 @@ func Example() {
1616
// setting contextual log entry
1717
ctx := logctx.New(context.Background(), log.WithField("foo", "bar"))
1818

19+
// adding additional log field
20+
ctx = logctx.AddField(ctx, "bizz", "buzz")
21+
1922
// retrieving context log entry, adding some data and emitting the log
2023
logctx.From(ctx).Info("hello world")
21-
// Output: level=info msg="hello world" foo=bar
24+
// Output: level=info msg="hello world" bizz=buzz foo=bar
2225
}
2326

2427
// IMPORTANT: this test is a the end because it alters global Default,

0 commit comments

Comments
 (0)