callerfunc.go 718 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. //@File callerfunc.go
  2. //@Time 2022/05/16
  3. //@Author #Suyghur,
  4. package utils
  5. import (
  6. "fmt"
  7. "runtime"
  8. "strings"
  9. )
  10. func CallerFuncName() string {
  11. pc := make([]uintptr, 1)
  12. runtime.Callers(3, pc)
  13. f := runtime.FuncForPC(pc[0])
  14. return f.Name()
  15. }
  16. func CallerFuncLine() string {
  17. pc := make([]uintptr, 1)
  18. runtime.Callers(2, pc)
  19. f := runtime.FuncForPC(pc[0])
  20. file, line := f.FileLine(pc[0])
  21. return fmt.Sprintf("%s@%d", file, line)
  22. }
  23. func cleanUpFuncName(funcName string) string {
  24. end := strings.LastIndex(funcName, ".")
  25. if end == -1 {
  26. return ""
  27. }
  28. return funcName[end+1:]
  29. }
  30. func GetSelfFuncName() string {
  31. pc, _, _, _ := runtime.Caller(1)
  32. return cleanUpFuncName(runtime.FuncForPC(pc).Name())
  33. }