英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论