HiveBrain v1.2.0
Get Started
← Back to all entries
snippetgoCritical

How to dump goroutine stacktraces?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
goroutinehowstacktracesdump

Problem

I have Java background, and I love to use signal QUIT to inspect Java thread dump.

How to let Golang print out all goroutines stack trace?

Solution

To print the stack trace for the current goroutine, use PrintStack() from runtime/debug.



PrintStack prints to standard error the stack trace returned by Stack.


For example:

import(
   "runtime/debug"
)
...    
debug.PrintStack()


To print the stack trace for all goroutines use Lookup and WriteTo from runtime/pprof.

func Lookup(name string) *Profile
// Lookup returns the profile with the given name,
// or nil if no such profile exists.

func (p *Profile) WriteTo(w io.Writer, debug int) error
// WriteTo writes a pprof-formatted snapshot of the profile to w.
// If a write to w returns an error, WriteTo returns that error.
// Otherwise, WriteTo returns nil.



Each Profile has a unique name. A few profiles are predefined:


goroutine - stack traces of all current goroutines

heap - a sampling of all heap allocations

threadcreate - stack traces that led to the creation of new OS threads

block - stack traces that led to blocking on synchronization primitives

For example:

pprof.Lookup("goroutine").WriteTo(os.Stdout, 1)

Code Snippets

import(
   "runtime/debug"
)
...    
debug.PrintStack()
func Lookup(name string) *Profile
// Lookup returns the profile with the given name,
// or nil if no such profile exists.

func (p *Profile) WriteTo(w io.Writer, debug int) error
// WriteTo writes a pprof-formatted snapshot of the profile to w.
// If a write to w returns an error, WriteTo returns that error.
// Otherwise, WriteTo returns nil.
pprof.Lookup("goroutine").WriteTo(os.Stdout, 1)

Context

Stack Overflow Q#19094099, score: 187

Revisions (0)

No revisions yet.