golang在日志中打印堆棧信息


使用debug.Stack()

package main
 
import (
    "fmt"
    "runtime/debug"
)
 
func test1() {
    test2()
}
 
func test2() {
    test3()
}
 
func test3() {
    // 可以通過 debug.PrintStack() 直接打印,也可以通過 debug.Stack() 方法獲取堆棧然后自己打印
    fmt.Printf("%s", debug.Stack())
    debug.PrintStack()
}
 
func main() {
    test1()
}
 
------------------------------------
 
$ go run test_stacktrace.go
 
goroutine 1 [running]:
runtime/debug.Stack(0x0, 0x0, 0x0)
        /usr/lib/golang/src/runtime/debug/stack.go:24 +0x80
main.test3()
        /tmp/test_stacktrace.go:17 +0x24
main.test2()
        /tmp/test_stacktrace.go:13 +0x14
main.test1()
        /tmp/test_stacktrace.go:9 +0x14
main.main()
        /tmp/test_stacktrace.go:22 +0x14
 
goroutine 1 [running]:
runtime/debug.Stack(0x0, 0x0, 0x0)
        /usr/lib/golang/src/runtime/debug/stack.go:24 +0x80
runtime/debug.PrintStack()
        /usr/lib/golang/src/runtime/debug/stack.go:16 +0x18
main.test3()
        /tmp/test_stacktrace.go:18 +0x101
main.test2()
        /tmp/test_stacktrace.go:13 +0x14
main.test1()
        /tmp/test_stacktrace.go:9 +0x14
main.main()
        /tmp/test_stacktrace.go:22 +0x14
 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM