Skip to content

Commit

Permalink
added CallingFunction
Browse files Browse the repository at this point in the history
  • Loading branch information
ungerik committed Nov 6, 2024
1 parent 4c05038 commit 5502a8a
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
13 changes: 12 additions & 1 deletion callstack.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ func filePathPrefix() string {
}

func callstack(skip int) string {
skip = max(2+skip, 0) // Prefer robustness in logging over panics
skip = max(2+skip, 0) // Prefer robustness in logging over negative index panics
stack := make([]uintptr, 32)
n := runtime.Callers(skip, stack)
stack = stack[:n]
Expand All @@ -48,3 +48,14 @@ func callstack(skip int) string {
}
return b.String()
}

// CallingFunction returns the name of the function that called it.
func CallingFunction() string {
stack := make([]uintptr, 1)
n := runtime.Callers(2, stack)
if n == 0 {
// Should never happen, but better safe than sory because of a panic
return "UNKNOWN"
}
return runtime.FuncForPC(stack[0]).Name()
}
7 changes: 7 additions & 0 deletions callstack_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package golog

import "testing"

func TestCallingFunction(t *testing.T) {
t.Fatal(CallingFunction())
}

0 comments on commit 5502a8a

Please sign in to comment.