将堆栈跟踪放入字符串变量中。

huangapple go评论90阅读模式
英文:

put stack trace to string variable

问题

是否可以像这样放置堆栈跟踪...

goroutine 20 [running]:
runtime.panic(0x3a2820, 0xc2081ad4b0)
	/usr/local/go/src/pkg/runtime/panic.c:279 +0xf5
testing.func·006()
	/usr/local/go/src/pkg/testing/testing.go:416 +0x176
runtime.panic(0x3a2820, 0xc2081ad4b0)
	/usr/local/go/src/pkg/runtime/panic.c:248 +0x18d
my.Test(0x3a2820, 0xc2081acf20, 0x3a2820, 0xc2081acf30, 0xc208056000)
	/Users/usr/golang/src/my/testing.go:67 +0x572

...在字符串变量中进行重新格式化并剪切冗余信息。

这个伪代码可以这样写:

package main

import (
	"runtime"
)

func main() {
	var stackStr string
	stackStr = runtime.GetStackFromHere()
}

我尝试过 panic("give me stack trace from here"),但它只会将堆栈跟踪打印到控制台,而不是存储在 var string 中。

英文:

Is it possible to put stack trace like this ...

goroutine 20 [running]:
runtime.panic(0x3a2820, 0xc2081ad4b0)
	/usr/local/go/src/pkg/runtime/panic.c:279 +0xf5
testing.func·006()
	/usr/local/go/src/pkg/testing/testing.go:416 +0x176
runtime.panic(0x3a2820, 0xc2081ad4b0)
	/usr/local/go/src/pkg/runtime/panic.c:248 +0x18d
my.Test(0x3a2820, 0xc2081acf20, 0x3a2820, 0xc2081acf30, 0xc208056000)
	/Users/usr/golang/src/my/testing.go:67 +0x572

... in string variable for reformating it and cut off redundunt information for me.

This pseudo code would be like this:

package main

import (
	"runtime"
)

func main() {
	var stackStr string
	stackStr = runtime.GetStackFromHere()
}

I tried panic("give me stack trace from here") but it prints stack trace not in var string but only to console.

答案1

得分: 9

使用runtime.Stack函数获取堆栈跟踪:

b := make([]byte, 2048) // 调整缓冲区大小以大于预期的堆栈大小
n := runtime.Stack(b, false)
s := string(b[:n])

另一种方法是在循环中调用runtime.Caller并将堆栈跟踪格式化到缓冲区中。

英文:

Use the runtime.Stack function to get the stack trace:

b := make([]byte, 2048) // adjust buffer size to be larger than expected stack
n := runtime.Stack(b, false)
s := string(b[:n])

An alternative approach is to call runtime.Caller in a loop and format the stack trace to a buffer.

huangapple
  • 本文由 发表于 2015年2月25日 14:14:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/28712397.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定