Skip to content

Commit

Permalink
feature: add FromContextWithFields, add FromContextWithStd
Browse files Browse the repository at this point in the history
  • Loading branch information
Ak-Army committed Aug 29, 2024
1 parent ed92be5 commit da4848d
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
24 changes: 24 additions & 0 deletions handler.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
//go:build go1.7
// +build go1.7

package xlog
Expand Down Expand Up @@ -44,6 +45,29 @@ func FromContext(ctx context.Context) Logger {
return l
}

// FromContextWithStd gets the logger out of the context.
// If not logger is stored in the context, a GetLogger is returned.
func FromContextWithStd(ctx context.Context) Logger {
if ctx == nil {
return GetLogger()
}
l, ok := ctx.Value(logKey).(Logger)
if !ok {
return GetLogger()
}
return l
}

// FromContextWithFields gets the logger out of the context.
// If not logger is stored in the context, a GetLogger is returned.
func FromContextWithFields(ctx context.Context, fields F) Logger {
l := FromContextWithStd(ctx)
l = Copy(l)
l.SetFields(fields)

return l
}

// FromRequest gets the logger in the request's context.
// This is a shortcut for xlog.FromContext(r.Context())
func FromRequest(r *http.Request) Logger {
Expand Down
22 changes: 22 additions & 0 deletions handler_test.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
//go:build go1.7
// +build go1.7

package xlog
Expand All @@ -20,6 +21,27 @@ func TestFromContext(t *testing.T) {
assert.Equal(t, l, FromContext(ctx))
}

func TestFromContextWithStd(t *testing.T) {
assert.Equal(t, GetLogger(), FromContextWithStd(nil))
assert.Equal(t, GetLogger(), FromContextWithStd(context.Background()))
l := &logger{}
ctx := NewContext(context.Background(), l)
assert.Equal(t, l, FromContext(ctx))
}

func TestFromContextWithFields(t *testing.T) {
fields := F{"a": "a"}
l := GetLogger()
expected := Copy(l)
expected.SetFields(fields)
assert.Equal(t, expected, FromContextWithFields(nil, fields))
assert.Equal(t, expected, FromContextWithFields(context.Background(), fields))
nl := &logger{}
ctx := NewContext(context.Background(), nl)

assert.Equal(t, &logger{fields: fields}, FromContextWithFields(ctx, fields))
}

func TestNewHandler(t *testing.T) {
c := Config{
Level: LevelInfo,
Expand Down

0 comments on commit da4848d

Please sign in to comment.