Skip to content

Commit

Permalink
pass program counter to CallerMarshalFunc (#457)
Browse files Browse the repository at this point in the history
  • Loading branch information
Hades32 authored Jul 29, 2022
1 parent 4099072 commit d894f12
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 8 deletions.
4 changes: 2 additions & 2 deletions event.go
Original file line number Diff line number Diff line change
Expand Up @@ -744,11 +744,11 @@ func (e *Event) caller(skip int) *Event {
if e == nil {
return e
}
_, file, line, ok := runtime.Caller(skip + e.skipFrame)
pc, file, line, ok := runtime.Caller(skip + e.skipFrame)
if !ok {
return e
}
e.buf = enc.AppendString(enc.AppendKey(e.buf, CallerFieldName), CallerMarshalFunc(file, line))
e.buf = enc.AppendString(enc.AppendKey(e.buf, CallerFieldName), CallerMarshalFunc(pc, file, line))
return e
}

Expand Down
2 changes: 1 addition & 1 deletion globals.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ var (
CallerSkipFrameCount = 2

// CallerMarshalFunc allows customization of global caller marshaling
CallerMarshalFunc = func(file string, line int) string {
CallerMarshalFunc = func(pc uintptr, file string, line int) string {
return file + ":" + strconv.Itoa(line)
}

Expand Down
10 changes: 5 additions & 5 deletions log_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -782,7 +782,7 @@ func TestCallerMarshalFunc(t *testing.T) {

// test default behaviour this is really brittle due to the line numbers
// actually mattering for validation
_, file, line, _ := runtime.Caller(0)
pc, file, line, _ := runtime.Caller(0)
caller := fmt.Sprintf("%s:%d", file, line+2)
log.Log().Caller().Msg("msg")
if got, want := decodeIfBinaryToString(out.Bytes()), `{"caller":"`+caller+`","message":"msg"}`+"\n"; got != want {
Expand All @@ -793,16 +793,16 @@ func TestCallerMarshalFunc(t *testing.T) {
// test custom behavior. In this case we'll take just the last directory
origCallerMarshalFunc := CallerMarshalFunc
defer func() { CallerMarshalFunc = origCallerMarshalFunc }()
CallerMarshalFunc = func(file string, line int) string {
CallerMarshalFunc = func(pc uintptr, file string, line int) string {
parts := strings.Split(file, "/")
if len(parts) > 1 {
return strings.Join(parts[len(parts)-2:], "/") + ":" + strconv.Itoa(line)
}

return file + ":" + strconv.Itoa(line)
return runtime.FuncForPC(pc).Name() + ":" + file + ":" + strconv.Itoa(line)
}
_, file, line, _ = runtime.Caller(0)
caller = CallerMarshalFunc(file, line+2)
pc, file, line, _ = runtime.Caller(0)
caller = CallerMarshalFunc(pc, file, line+2)
log.Log().Caller().Msg("msg")
if got, want := decodeIfBinaryToString(out.Bytes()), `{"caller":"`+caller+`","message":"msg"}`+"\n"; got != want {
t.Errorf("invalid log output:\ngot: %v\nwant: %v", got, want)
Expand Down

0 comments on commit d894f12

Please sign in to comment.