Skip to content

Commit

Permalink
optimize: add WithCallerSkipFrameCount (#35)
Browse files Browse the repository at this point in the history
  • Loading branch information
li-jin-gou authored Jun 19, 2023
1 parent d6d12b3 commit 00fc458
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
9 changes: 9 additions & 0 deletions zerolog/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
25 changes: 25 additions & 0 deletions zerolog/options_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"))
Expand Down

0 comments on commit 00fc458

Please sign in to comment.