From 00fc458d8f950a2c29d492a6403b981c2c1afb6a Mon Sep 17 00:00:00 2001 From: kinggo Date: Mon, 19 Jun 2023 11:42:27 +0800 Subject: [PATCH] optimize: add WithCallerSkipFrameCount (#35) --- zerolog/options.go | 9 +++++++++ zerolog/options_test.go | 25 +++++++++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/zerolog/options.go b/zerolog/options.go index ebaf4b6..e95ed7d 100644 --- a/zerolog/options.go +++ b/zerolog/options.go @@ -97,6 +97,15 @@ func WithCaller() Opt { } } +// WithCallerSkipFrameCount adds a caller field to the logger's context +// The specified skipFrameCount int will override the global CallerSkipFrameCount for this context's respective logger. +// If set to -1 the global CallerSkipFrameCount will be used. +func WithCallerSkipFrameCount(skipFrameCount int) Opt { + return func(opts *Options) { + opts.context = opts.context.CallerWithSkipFrameCount(skipFrameCount) + } +} + // WithHook adds a hook to the logger's context func WithHook(hook zerolog.Hook) Opt { return func(opts *Options) { diff --git a/zerolog/options_test.go b/zerolog/options_test.go index 9dcb14b..8b882c6 100644 --- a/zerolog/options_test.go +++ b/zerolog/options_test.go @@ -68,6 +68,31 @@ func TestWithCaller(t *testing.T) { assert.Equal(t, filePath, "logger.go") } +func TestWithCallerSkipFrameCount(t *testing.T) { + b := &bytes.Buffer{} + l := New(WithCallerSkipFrameCount(5)) + l.SetOutput(b) + hlog.SetLogger(l) + hlog.Info("foobar") + + type Log struct { + Level string `json:"level"` + Caller string `json:"caller"` + Message string `json:"message"` + } + + log := &Log{} + + err := json.Unmarshal(b.Bytes(), log) + + assert.NoError(t, err) + + segments := strings.Split(log.Caller, ":") + filePath := filepath.Base(segments[0]) + + assert.Equal(t, filePath, "options_test.go") +} + func TestWithField(t *testing.T) { b := &bytes.Buffer{} l := New(WithField("service", "logging"))