當前位置: 首頁>>代碼示例>>Golang>>正文


Golang runtime.Caller函數代碼示例

本文整理匯總了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)
		}
	}
}
開發者ID:nuin,項目名稱:ampify,代碼行數:32,代碼來源:gocheck.go

示例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"))
}
開發者ID:wallyqs,項目名稱:util,代碼行數:30,代碼來源:testtool.go

示例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)
		}
	}
}
開發者ID:rocky,項目名稱:ssa-interp,代碼行數:26,代碼來源:rtcall.go

示例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
		}
	}
}
開發者ID:jmptrader,項目名稱:go-utils-1,代碼行數:35,代碼來源:tls.go

示例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)
}
開發者ID:MorpheusXAUT,項目名稱:logrus_fluent,代碼行數:29,代碼來源:fluent.go

示例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()
}
開發者ID:road0001,項目名稱:v2ray-core,代碼行數:36,代碼來源:subject.go

示例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
}
開發者ID:MoonighT,項目名稱:logger,代碼行數:31,代碼來源:logger.go

示例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
}
開發者ID:jim-slattery-rs,項目名稱:goa,代碼行數:39,代碼來源:runner.go

示例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())
}
開發者ID:magastzheng,項目名稱:go-2,代碼行數:25,代碼來源:t_run.go

示例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
}
開發者ID:jianjunliu,項目名稱:goa,代碼行數:37,代碼來源:runner.go

示例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)
}
開發者ID:evaluation-alex,項目名稱:gosync,代碼行數:31,代碼來源:gocheck.go

示例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...")
}
開發者ID:slowfei,項目名稱:gosfcore,代碼行數:31,代碼來源:SFDebug.go

示例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)
		}
	}
}
開發者ID:wutaizeng,項目名稱:kapacitor,代碼行數:32,代碼來源:stack_test.go

示例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
}
開發者ID:henrylee2cn,項目名稱:godocdown,代碼行數:28,代碼來源:terst.go

示例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))
	}
}
開發者ID:zchtodd,項目名稱:game,代碼行數:7,代碼來源:parse.go


注:本文中的runtime.Caller函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。