Verified Commit 74eefd75 authored by Cui's avatar Cui

add detect caller name tools

parent 87bfadfd
/*
* @Author: cuiweiqiang
* @Date: 2019-01-17 10:17
*/
package utils
import (
"runtime"
)
func GetCurrentFunctionName() string {
return getFrame(1).Function
}
func GetCallerFunctionName() string {
return getFrame(2).Function
}
func getFrame(skipFrames int) runtime.Frame {
targetFrameIndex := skipFrames + 2
programCounters := make([]uintptr, targetFrameIndex+2)
n := runtime.Callers(0, programCounters)
frame := runtime.Frame{Function: "unknown"}
if n > 0 {
frames := runtime.CallersFrames(programCounters[:n])
for more, frameIndex := true, 0; more && frameIndex <= targetFrameIndex; frameIndex++ {
var frameCandidate runtime.Frame
frameCandidate, more = frames.Next()
if frameIndex == targetFrameIndex {
frame = frameCandidate
}
}
}
return frame
}
/*
* @Author: cuiweiqiang
* @Date: 2019-01-17 10:30
*/
package utils
import (
"testing"
)
func TestGetCurrentFunctionName(t *testing.T) {
funcName := GetCurrentFunctionName()
if funcName == "gitlab.qingclass.cn/cuiweiqiang/utils.TestGetCurrentFunctionName" {
t.Log("success")
} else {
t.Failed()
}
}
func TestGetCallerFunctionName(t *testing.T) {
callerName := GetCallerFunctionName()
if callerName == "testing.tRunner" {
t.Log("success")
} else {
t.Failed()
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment