本文整理汇总了Golang中runtime.Caller函数的典型用法代码示例。如果您正苦于以下问题:Golang Caller函数的具体用法?Golang Caller怎么用?Golang Caller使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Caller函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: logCaller
func (c *C) logCaller(skip int, issue string) {
// This is a bit heavier than it ought to be.
skip += 1 // Our own frame.
if pc, callerFile, callerLine, ok := runtime.Caller(skip); ok {
var testFile string
var testLine int
testFunc := runtime.FuncForPC(c.method.Get())
if runtime.FuncForPC(pc) != testFunc {
for {
skip += 1
if pc, file, line, ok := runtime.Caller(skip); ok {
// Note that the test line may be different on
// distinct calls for the same test. Showing
// the "internal" line is helpful when debugging.
if runtime.FuncForPC(pc) == testFunc {
testFile, testLine = file, line
break
}
} else {
break
}
}
}
if testFile != "" && (testFile != callerFile ||
testLine != callerLine) {
c.logf("%s:%d > %s:%d:\n... %s", nicePath(testFile), testLine,
nicePath(callerFile), callerLine, issue)
} else {
c.logf("%s:%d:\n... %s", nicePath(callerFile), callerLine, issue)
}
}
}
示例2: Fatalf
// This function wraps Fatalf in order to provide a functional stack trace
// on failures rather than just a line number of the failing check. This
// helps if you have a test that fails in a loop since it will show
// the path to get there as well as the error directly.
func Fatalf(l Logger, f string, args ...interface{}) {
lines := make([]string, 0, 100)
msg := fmt.Sprintf(f, args...)
lines = append(lines, msg)
// Get the directory of testtool in order to ensure that we don't show
// it in the stack traces (it can be spammy).
_, myfile, _, _ := runtime.Caller(0)
mydir := path.Dir(myfile)
// Generate the Stack of callers:
for i := 0; true; i++ {
_, file, line, ok := runtime.Caller(i)
if ok == false {
break
}
// Don't print the stack line if its within testtool since its
// annoying to see the testtool internals.
if path.Dir(file) == mydir {
continue
}
msg := fmt.Sprintf("%d - %s:%d", i, file, line)
lines = append(lines, msg)
}
l.Fatalf("%s", strings.Join(lines, "\n"))
}
示例3: caller
func caller() {
//FIXME add a test to make sure file, pc from Callers matches
// the equivalent from Caller.
for i := 0; i < 2; i++ {
_, _, _, ok := runtime.Caller(i)
if !ok {
panic(i)
}
}
_, _, _, ok := runtime.Caller(20)
if ok {
panic(3)
}
pcA := make([]uintptr, 6, 6)
count := runtime.Callers(0, pcA)
pcB := make([]uintptr, 6, 6)
countM1 := runtime.Callers(1, pcB)
if count-1 != countM1 {
panic(5)
}
for i := 1; i < countM1-1; i++ {
if pcA[i+1] != pcB[i] {
panic(100 + i)
}
}
}
示例4: callerPkgDir
// callerPkgDir returns a pathname containing the build-time location of the
// deepest calling function that is not within this package. If that cannot be
// found, ok will be false and dir will be empty.
func callerPkgDir() (dir string, ok bool) {
_, thisFile, _, cok := runtime.Caller(0) // /home/me/workspace/src/fastly/go-utils/tls/tls.go
if !cok {
return
}
thisDir := filepath.Dir(thisFile) // /home/me/workspace/src/fastly/go-utils/tls
sep := fmt.Sprintf("%csrc%c", os.PathSeparator, os.PathSeparator) // /src/
p := strings.SplitN(thisDir, sep, 2)
if len(p) < 2 {
return
}
thisPkg := p[1] // fastly/go-utils/tls/
for i := 1; ; i++ {
if i > 10 {
// typical stack is tls.ConfigureServer -> tls.GenerateConfig ->
// tls.LoadPackagedKeypair -> tls.LocatePackagedPEMFile ->
// tls.LocatePackagedPEMDir -> tls.searchUpwards
panic("excessive recursion inside tls package")
}
_, file, _, cok := runtime.Caller(i) // /home/me/workspace/src/foo/bar/subpkg/thing.go
if !cok {
return
}
if !strings.Contains(file, thisPkg) {
return filepath.Dir(file), true // /home/me/workspace/src/foo/bar/subpkg
}
}
}
示例5: setCaller
func setCaller(entry *logrus.Entry, skip int) {
_, file, line, ok := runtime.Caller(skip)
if !ok {
file = "???"
line = 0
} else {
i := 1
for strings.Contains(file, "logrus/") {
_, fileHigher, lineHigher, okHigher := runtime.Caller(skip + i)
if okHigher {
file = fileHigher
line = lineHigher
}
i++
}
lastSlash := strings.LastIndex(file, "/")
if lastSlash >= 0 {
folderSlash := strings.LastIndex(file[:lastSlash], "/")
if folderSlash >= 0 {
file = file[folderSlash+1:]
} else {
file = file[lastSlash+1:]
}
}
}
entry.Data["caller"] = fmt.Sprintf("%s:%d", file, line)
}
示例6: decorate
// decorate prefixes the string with the file and line of the call site
// and inserts the final newline if needed and indentation tabs for formatting.
func decorate(s string) string {
_, file, line, ok := runtime.Caller(3)
if strings.Contains(file, "testing") {
_, file, line, ok = runtime.Caller(4)
}
if ok {
// Truncate file name at last file name separator.
if index := strings.LastIndex(file, "/"); index >= 0 {
file = file[index+1:]
} else if index = strings.LastIndex(file, "\\"); index >= 0 {
file = file[index+1:]
}
} else {
file = "???"
line = 1
}
buf := new(bytes.Buffer)
// Every line is indented at least one tab.
buf.WriteString(" ")
fmt.Fprintf(buf, "%s:%d: ", file, line)
lines := strings.Split(s, "\n")
if l := len(lines); l > 1 && lines[l-1] == "" {
lines = lines[:l-1]
}
for i, line := range lines {
if i > 0 {
// Second and subsequent lines are indented an extra tab.
buf.WriteString("\n\t\t")
}
buf.WriteString(line)
}
buf.WriteByte('\n')
return buf.String()
}
示例7: getActualCaller
func getActualCaller() (file string, line int, ok bool) {
cpc, _, _, ok := runtime.Caller(2)
if !ok {
return
}
callerFunPtr := runtime.FuncForPC(cpc)
if callerFunPtr == nil {
ok = false
return
}
var pc uintptr
for callLevel := 3; callLevel < 5; callLevel++ {
pc, file, line, ok = runtime.Caller(callLevel)
if !ok {
return
}
funcPtr := runtime.FuncForPC(pc)
if funcPtr == nil {
ok = false
return
}
if getFuncNameWithoutPackage(funcPtr.Name()) !=
getFuncNameWithoutPackage(callerFunPtr.Name()) {
return
}
}
ok = false
return
}
示例8: computeErrorLocation
// computeErrorLocation implements a heuristic to find the location in the user
// code where the error occurred. It walks back the callstack until the file
// doesn't match "/goa/design/*.go" or one of the DSL package paths.
// When successful it returns the file name and line number, empty string and
// 0 otherwise.
func computeErrorLocation() (file string, line int) {
skipFunc := func(file string) bool {
if strings.HasSuffix(file, "_test.go") { // Be nice with tests
return false
}
file = filepath.ToSlash(file)
for pkg := range dslPackages {
if strings.Contains(file, pkg) {
return true
}
}
return false
}
depth := 2
_, file, line, _ = runtime.Caller(depth)
for skipFunc(file) {
depth++
_, file, line, _ = runtime.Caller(depth)
}
wd, err := os.Getwd()
if err != nil {
return
}
wd, err = filepath.Abs(wd)
if err != nil {
return
}
f, err := filepath.Rel(wd, file)
if err != nil {
return
}
file = f
return
}
示例9: test2
func test2() {
pc, file, line, ok := runtime.Caller(2)
log.Println(pc)
log.Println(file)
log.Println(line)
log.Println(ok)
f := runtime.FuncForPC(pc)
log.Println(f.Name())
pc, file, line, ok = runtime.Caller(0)
log.Println(pc)
log.Println(file)
log.Println(line)
log.Println(ok)
f = runtime.FuncForPC(pc)
log.Println(f.Name())
pc, file, line, ok = runtime.Caller(1)
log.Println(pc)
log.Println(file)
log.Println(line)
log.Println(ok)
f = runtime.FuncForPC(pc)
log.Println(f.Name())
}
示例10: computeErrorLocation
// computeErrorLocation implements a heuristic to find the location in the user
// code where the error occurred. It walks back the callstack until the file
// doesn't match "/goa/design/*.go".
// When successful it returns the file name and line number, empty string and
// 0 otherwise.
func computeErrorLocation() (file string, line int) {
depth := 2
_, file, line, _ = runtime.Caller(depth)
ok := strings.HasSuffix(file, "_test.go") // Be nice with tests
if !ok {
nok, _ := regexp.MatchString(`/goa/design/.+\.go$`, file)
ok = !nok
}
for !ok {
depth++
_, file, line, _ = runtime.Caller(depth)
ok = strings.HasSuffix(file, "_test.go")
if !ok {
nok, _ := regexp.MatchString(`/goa/design/.+\.go$`, file)
ok = !nok
}
}
wd, err := os.Getwd()
if err != nil {
return
}
wd, err = filepath.Abs(wd)
if err != nil {
return
}
f, err := filepath.Rel(wd, file)
if err != nil {
return
}
file = f
return
}
示例11: logCaller
func (c *C) logCaller(skip int) {
// This is a bit heavier than it ought to be.
skip += 1 // Our own frame.
pc, callerFile, callerLine, ok := runtime.Caller(skip)
if !ok {
return
}
var testFile string
var testLine int
testFunc := runtime.FuncForPC(c.method.PC())
if runtime.FuncForPC(pc) != testFunc {
for {
skip += 1
if pc, file, line, ok := runtime.Caller(skip); ok {
// Note that the test line may be different on
// distinct calls for the same test. Showing
// the "internal" line is helpful when debugging.
if runtime.FuncForPC(pc) == testFunc {
testFile, testLine = file, line
break
}
} else {
break
}
}
}
if testFile != "" && (testFile != callerFile || testLine != callerLine) {
c.logCode(testFile, testLine)
}
c.logCode(callerFile, callerLine)
}
示例12: Break
// break
func Break(format bool, v ...interface{}) {
fmt.Println("Variables:")
Fdump(os.Stdout, format, v...)
var pc, file, line, ok = runtime.Caller(1)
if ok {
fmt.Printf("\n\n[Debug] %s() [%s:%d]\n[Stack]\n", runtime.FuncForPC(pc).Name(), file, line)
}
for i := 2; ; i++ {
pc, file, line, ok := runtime.Caller(i)
if !ok {
break
}
fn := runtime.FuncForPC(pc).Name()
if 0 != len(file) {
// /usr/local/go/src/pkg/runtime/proc.c:1223 (0x173d0)
fmt.Printf("%s(...)\n%s:%d (0x%x)\n", fn, file, line, pc)
} else {
// runtime.goexit(...)
// L1223: runtime.goexit(...) (0x173d0)
fmt.Printf("L%d: %s(...) (0x%x)\n", line, fn, pc)
}
}
fmt.Println("\nPress Enter to Continue")
fmt.Scanln()
fmt.Println("Break End...")
}
示例13: TestFrameLine
func TestFrameLine(t *testing.T) {
var tests = []struct {
Frame
want int
}{{
Frame(initpc),
9,
}, {
func() Frame {
var pc, _, _, _ = runtime.Caller(0)
return Frame(pc)
}(),
20,
}, {
func() Frame {
var pc, _, _, _ = runtime.Caller(1)
return Frame(pc)
}(),
28,
}, {
Frame(0), // invalid PC
0,
}}
for _, tt := range tests {
got := tt.Frame.line()
want := tt.want
if want != got {
t.Errorf("Frame(%v): want: %v, got: %v", uintptr(tt.Frame), want, got)
}
}
}
示例14: findDepth
func (self *Tester) findDepth() int {
height := 1 // Skip us
for {
pc, _, _, ok := runtime.Caller(height)
function := runtime.FuncForPC(pc)
if !ok {
// Got too close to the sun
if false {
for ; height > 0; height-- {
pc, _, _, ok := runtime.Caller(height)
fmt.Printf("[%d %v %v]", height, pc, ok)
if ok {
function := runtime.FuncForPC(pc)
fmt.Printf(" => [%s]", function.Name())
}
fmt.Printf("\n")
}
}
return 1
}
functionEntry := function.Entry()
if functionEntry == self.focusEntry || functionEntry == self.testEntry {
return height - 1 // Not the surrounding test function, but within it
}
height += 1
}
return 1
}
示例15: debug
func (p *Parser) debug(value string) {
if p.Logdebug {
_, _, line1, _ := runtime.Caller(1)
_, _, line2, _ := runtime.Caller(2)
fmt.Println(fmt.Sprintf("debug: %s (%d from %d)", value, line1, line2))
}
}