CodeBlanks Logo Icon CodeBlanks

runtime.Stack

Learn to get a goroutine's stack trace with Stack.

runtime.Stack

runtime.Stack(buf, all) writes the call stack as text into a buffer. If all is true, every goroutine's stack is written; this is very valuable when diagnosing a stuck service.

buf := make([]byte, 1<<16)
n := runtime.Stack(buf, true)
os.Stderr.Write(buf[:n])

For the current goroutine only, debug.Stack() or debug.PrintStack() is shorter.

runtime.Caller

runtime.Caller(skip) returns the caller's file name and line; logging libraries add line information this way:

func nerede() string {
    _, dosya, satir, ok := runtime.Caller(1)
    if !ok { return "?" }
    return fmt.Sprintf("%s:%d", filepath.Base(dosya), satir)
}

skip=0 refers to the function calling Caller, 1 to its caller.

Practice Search the stack

Write a function called calisan(); inside it call runtime.Stack(buf, false) with buf := make([]byte, 4096) and return whether the stack text contains "main.calisan" using strings.Contains. Print the result.

Starter code

main.go
package main

import (
    "fmt"
    "runtime"
    "strings"
)

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import (
    "fmt"
    "runtime"
    "strings"
)

func calisan() bool {
    buf := make([]byte, 4096)
    n := runtime.Stack(buf, false)
    return strings.Contains(string(buf[:n]), "main.calisan")
}

func main() {
    fmt.Println(calisan())
}

Expected output

true

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 How do you get all goroutine stacks of a running Go process without changing code?

  • With GOGC=off
  • It isn't possible
  • By sending SIGQUIT (Ctrl+\) Correct answer
  • By sending SIGINT

Explanation: On SIGQUIT the Go runtime writes all goroutine stacks to stderr and exits; GOTRACEBACK=all increases the detail.

2 All goroutines

Question
n := runtime.Stack(buf, ____)
Answer
n := runtime.Stack(buf, true)

Explanation: With the second argument true, every goroutine's stack is written.

3 Tool and output

Term Meaning
runtime.Stack(buf, true) All stacks
debug.Stack() Current goroutine
runtime.Caller(1) File and line
SIGQUIT Stack dump and exit

All lessons in Expert