Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

logctx.AddField(ctx, key, value) added #7

Merged
merged 1 commit into from
Feb 14, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ Small, easy to use, yet powerful utility packages for [**logrus**](https://githu

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

Add a log entry to the context using `logctx.New(ctx, logEntry)`. Retrieve the log entry using `logctx.From(ctx)`.
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)`.

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

Expand Down
6 changes: 6 additions & 0 deletions logctx/logctx.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,9 @@ func From(ctx context.Context) *logrus.Entry {
}
return Default
}

// AddField adds a log field to the contexual log entry.
func AddField(ctx context.Context, key string, value interface{}) context.Context {
entry := From(ctx).WithField(key, value)
return New(ctx, entry)
}
5 changes: 4 additions & 1 deletion logctx/logctx_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,12 @@ func Example() {
// setting contextual log entry
ctx := logctx.New(context.Background(), log.WithField("foo", "bar"))

// adding additional log field
ctx = logctx.AddField(ctx, "bizz", "buzz")

// retrieving context log entry, adding some data and emitting the log
logctx.From(ctx).Info("hello world")
// Output: level=info msg="hello world" foo=bar
// Output: level=info msg="hello world" bizz=buzz foo=bar
}

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