150

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?

2

11 Answers 11

167

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)
8
  • 1
    Does it print stack trace of all goroutines?
    – user972946
    Sep 30, 2013 at 12:50
  • 1
    Sorry, it prints the current goroutine stack trace only.
    – user972946
    Oct 1, 2013 at 2:48
  • 4
    @HowardGuo I've added an example using runtime/pprof to dump all stack traces. Oct 1, 2013 at 3:16
  • 1
    thank you very much. may I suggest using WriteTo(os.Stdout, 1) instead of 0? so that stack trace information will contain actual symbol instead of memory address.
    – user972946
    Oct 2, 2013 at 22:50
  • 2
    I think this only outputs each thread's currently running goroutine, not all goroutines, ex: play.golang.org/p/0hVB0_LMdm
    – rogerdpack
    Jul 11, 2014 at 20:28
50

There is an HTTP frontend for the runtime/pprof package mentioned in Intermernet's answer. Import the net/http/pprof package to register an HTTP handler for /debug/pprof:

import _ "net/http/pprof"
import _ "net/http"

Start an HTTP listener if you do not have one already:

go func() {
    log.Println(http.ListenAndServe("localhost:6060", nil))
}()

Then point a browser to http://localhost:6060/debug/pprof for a menu, or http://localhost:6060/debug/pprof/goroutine?debug=2 for a full goroutine stack dump.

There are other fun things you can learn about your running code this way too. Check out the blog post for examples and more details: http://blog.golang.org/profiling-go-programs

1
  • i made it run by it only shows the goroutines executed as far I see. Is there any way I could see all the "methods" that are executed after the main.go launches? Mar 22, 2018 at 19:51
46

Similar to Java, SIGQUIT can be used to print a stack trace of a Go program and its goroutines.
A key difference, however, is that by default sending SIGQUIT to Java programs do not terminate them, while Go programs do exit.

This approach requires no code change to print a stack trace of all goroutines of existing programs.

The environment variable GOTRACEBACK (see documentation of the runtime package) controls the amount of output generated. For example, to include all goroutines, set GOTRACEBACK=all.

The printing of the stack trace is triggered by an unexpected runtime condition (unhandled signal), originally documented in this commit, making it available since at least Go 1.1.


Alternatively, if modifying source code is an option, see other answers.


Note that in a Linux terminal, SIGQUIT can be conveniently sent with the key combination Ctrl+\.

3
  • 6
    While looking through docs I didn't find any mentions of SIGQUIT, rather SIGABRT. From my own tests (with go 1.7) the latter also worked over the former.
    – soltysh
    Apr 19, 2017 at 15:36
  • 4
    this should be the top answer. Mar 1, 2019 at 0:04
  • The docs refer to "when a Go program fails due to an unrecovered panic or an unexpected runtime condition". An uncaught signal (SIGQUIT, etc) is one of the latter. Why did I mention SIGQUIT? Because the OP expresses their love for using SIGQUIT with Java, and this answer emphasizes the similarity. Rewording the answer to make it clearer. Sep 27, 2019 at 18:09
45

To mimic the Java behaviour of stack-dump on SIGQUIT but still leaving the program running:

go func() {
    sigs := make(chan os.Signal, 1)
    signal.Notify(sigs, syscall.SIGQUIT)
    buf := make([]byte, 1<<20)
    for {
        <-sigs
        stacklen := runtime.Stack(buf, true)
        log.Printf("=== received SIGQUIT ===\n*** goroutine dump...\n%s\n*** end\n", buf[:stacklen])
    }
}()
4
  • 5
    I think this is what the author was really looking for- mimics what Java does when you send a kill -QUIT. One small change I had to make was to change the first line of the for() loop to: "<- sigs". In other words, just discard the signal after waiting on it. Recent versions of Go will not let you declare a variable without later using it. Mar 25, 2015 at 13:17
  • @Bryan, are you willing to license this under BSD or other more-permissive terms additional to the CC-BY-SA 3.0 required by StackOverflow? Jan 21, 2018 at 19:59
  • 1
    @CharlesDuffy you can find much the same thing here under Apache licence: github.com/weaveworks/weave/blob/…
    – Bryan
    Jan 22, 2018 at 15:16
  • I slightly improved this to print debug if it receives an os.Interupt signal, if a second signal comes in quickly (< 1 second) it exits, play.golang.org/p/dWgWrDFBOth
    – user4466350
    Aug 19, 2021 at 10:16
30

You can use runtime.Stack to get the stack trace of all goroutines:

buf := make([]byte, 1<<16)
runtime.Stack(buf, true)
fmt.Printf("%s", buf)

From the documentation:

func Stack(buf []byte, all bool) int

Stack formats a stack trace of the calling goroutine into buf and returns the number of bytes written to buf. If all is true, Stack formats stack traces of all other goroutines into buf after the trace for the current goroutine.

7
  • This includes backtraces from all goroutines, nice!
    – rogerdpack
    Jul 11, 2014 at 20:39
  • 3
    Don't forget to add string(buf) or you'll print the raw bytes there.
    – koda
    May 18, 2015 at 18:21
  • 3
    Maybe I'm doing something wrong, or perhaps the functionality has changed, but this doesn't retrieve anything for me except an empty slice of bytes?
    – 17xande
    Nov 3, 2016 at 12:42
  • 1
    @koda there is no need to do string(buf) here, fmt.Printf("%s", buf) and fmt.Printf("%s", string(buf)) do the exact same thing (see docs for fmt package); the only difference here is that the string version will copy the bytes from buf needlessly
    – kbolino
    Feb 10, 2018 at 17:54
  • 1
    note that runtime.Stack returns the number of bytes it actually wrote inside buf and so you should manually slice buf to that length when printing it, to avoid writing a bunch of 0 bytes (which may be ignored by terminals but will show up in a file that output is redirected to)
    – kbolino
    Feb 10, 2018 at 18:04
29

Press CTRL+\

(If you run it in a terminal and just want to kill your program and dump the go routines etc)

I found this question looking for the key sequence. Just wanted a quick and easy way to tell if my program is leaking go routines :)

3
  • 1
    This is why I love Go so much. It has all these features that make it way better than C or C++. May 26, 2022 at 13:16
  • 3
    @user1766438 Ctrl+\ is the default terminal key sequence for SIGQUIT and has nothing to do with golang
    – phuclv
    May 27, 2022 at 4:23
  • 2
    @phuclv yes but a C++ -compiled program doesn't print the stack trace when receiving SIGQUIT
    – arainone
    Jan 25 at 10:31
14

On *NIX systems (including OSX) send a signal abort SIGABRT:

pkill -SIGABRT program_name

2
  • Apparently, sending SIGQUIT to a Java process does not terminate it like SIGABRT will.
    – Dave C
    Aug 26, 2015 at 19:24
  • I found this to be the simplest and most matching solution to the original question. Often you need a stacktrace right away, without changing your code.
    – jotrocken
    Apr 7, 2017 at 15:34
10

By default, press ^\ keys ( CTRL+\ ) to dump the stack traces of all goroutines.


Otherwise, for more granular control, you can use panic. The simple way as of Go 1.6+:

go func() {
    s := make(chan os.Signal, 1)
    signal.Notify(s, syscall.SIGQUIT)
    <-s
    panic("give me the stack")
}()

Then, run your program like so:

# Press ^\ to dump the stack traces of all the user-created goroutines
$ GOTRACEBACK=all go run main.go

If you also want to print go runtime goroutines:

$ GOTRACEBACK=system go run main.go

Here are all the GOTRACEBACK options:

  • GOTRACEBACK=none omits the goroutine stack traces entirely.
  • GOTRACEBACK=single (the default) behaves as described above.
  • GOTRACEBACK=all adds stack traces for all user-created goroutines.
  • GOTRACEBACK=system is like all but adds stack frames for run-time functions and shows goroutines created internally by the run-time.
  • GOTRACEBACK=crash is like system but crashes in an operating system-specific manner instead of exiting. For example, on Unix systems, the crash raises SIGABRT to trigger a core dump.

Here is the documentation

The GOTRACEBACK variable controls the amount of output generated when a Go program fails due to an unrecovered panic or an unexpected runtime condition.

By default, a failure prints a stack trace for the current goroutine, eliding functions internal to the run-time system, and then exits with exit code 2. The failure prints stack traces for all goroutines if there is no current goroutine or the failure is internal to the run-time.

For historical reasons, the GOTRACEBACK settings 0, 1, and 2 are synonyms for none, all, and system, respectively.

The runtime/debug package's SetTraceback function allows increasing the amount of output at run time, but it cannot reduce the amount below that specified by the environment variable. See https://golang.org/pkg/runtime/debug/#SetTraceback.

5

It's necessary to use the length returned by runtime.Stack() to avoid printing a bunch of empty lines after your stack trace. The following recovery function prints a nicely formatted trace:

if r := recover(); r != nil {
    log.Printf("Internal error: %v", r))
    buf := make([]byte, 1<<16)
    stackSize := runtime.Stack(buf, true)
    log.Printf("%s\n", string(buf[0:stackSize]))
}
4
  • There is no runtime.Trace; runtime.Stack was already mentioned a year and a half ago.
    – Dave C
    Jun 19, 2015 at 18:52
  • I've never seen that; what platform are you running on?
    – Bryan
    Nov 15, 2015 at 10:10
  • What is it you haven't seen? The code should run on all platforms; I've tested it on Windows 7, Ubuntu 14.04, and Mac. Nov 16, 2015 at 16:41
  • Never seen empty lines.
    – Bryan
    Jan 13, 2017 at 17:10
1

You can use this:

kill -3 YOUR_PROCESS_PID_ID
0

Package errors allows you to dump the error with stack trace. For example with the function WithStack

WithStack annotates err with a stack trace at the point WithStack was called

package main

import (
"fmt"

"github.com/pkg/errors"
)

func main() {
    cause := errors.New("whoops")
    err := errors.WithStack(cause)
    fmt.Printf("%+v", err)
}
1
  • 1
    fmt.Println does not print the stacktrace, you need to use for example fmt.Printf("%+v", err) instead, to have the stacktrace printed.
    – Honza
    Nov 28 at 9:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.