From da4848d9ccca9b964f71e2cde19dc0c8c74e1554 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hunyadv=C3=A1ri=20P=C3=A9ter?= Date: Thu, 29 Aug 2024 09:31:05 +0200 Subject: [PATCH] feature: add FromContextWithFields, add FromContextWithStd --- handler.go | 24 ++++++++++++++++++++++++ handler_test.go | 22 ++++++++++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/handler.go b/handler.go index 311b613..3ad9628 100644 --- a/handler.go +++ b/handler.go @@ -1,3 +1,4 @@ +//go:build go1.7 // +build go1.7 package xlog @@ -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 { diff --git a/handler_test.go b/handler_test.go index 69d3438..291ba06 100644 --- a/handler_test.go +++ b/handler_test.go @@ -1,3 +1,4 @@ +//go:build go1.7 // +build go1.7 package xlog @@ -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,