kjk
12/19/2013 - 5:43 AM

Shows that we can get the caller's function name without access to source code. go build -o test show_caller_name.go; rm show_caller_name.go

Shows that we can get the caller's function name without access to source code. go build -o test show_caller_name.go; rm show_caller_name.go; ./test

package main

import (
	"bytes"
	"fmt"
	"runtime"
)

var (
	dunno     = []byte("???")
	centerDot = []byte("·")
	dot       = []byte(".")
)

func function(pc uintptr) []byte {
	fn := runtime.FuncForPC(pc)
	if fn == nil {
		return dunno
	}
	name := []byte(fn.Name())
	// The name includes the path name to the package, which is unnecessary
	// since the file name is already included.  Plus, it has center dots.
	// That is, we see
	//      runtime/debug.*T·ptrmethod
	// and want
	//      *T.ptrmethod
	if period := bytes.Index(name, dot); period >= 0 {
		name = name[period+1:]
	}
	name = bytes.Replace(name, centerDot, dot, -1)
	return name
}

func showCallerName() {
	pc, _, _, ok := runtime.Caller(1)
	if !ok {
		fmt.Printf("runtime.Caller() failed\n")
		return
	}
	name := function(pc)
	fmt.Printf("Caller name: %s\n", name)
}

func myCaller() {
	showCallerName()
}

func main() {
	myCaller()
}