caller.go 720 B

12345678910111213141516171819202122232425262728293031323334353637
  1. package runtimeutil
  2. import (
  3. "fmt"
  4. "runtime"
  5. "strings"
  6. )
  7. // CallerFuncPos get caller's func name
  8. func CallerFuncPos(skip int) string {
  9. _, line, name := Caller(skip + 1)
  10. return fmt.Sprintf("%s:%d", name, line)
  11. }
  12. // CallerFuncPos get caller's func name
  13. func CallerFuncName(skip int) string {
  14. _, _, name := Caller(skip + 1)
  15. arr := strings.Split(name, "/")
  16. if len(arr) >= 3 {
  17. return strings.Join(arr[2:], ".")
  18. }
  19. return strings.Join(arr, ".")
  20. }
  21. // Caller file, file line, function name
  22. func Caller(skip int) (file string, line int, functionName string) {
  23. var (
  24. pc uintptr
  25. ok bool
  26. )
  27. pc, file, line, ok = runtime.Caller(skip + 1)
  28. if !ok {
  29. return
  30. }
  31. return file, line, runtime.FuncForPC(pc).Name()
  32. }