runtime/debug

Guided tour · Runtime & Debug · pkg.go.dev →

GC tuning, memory limits, stack traces, and build info.

GC and memory tuning

SetGCPercent

old := debug.SetGCPercent(200) // less frequent GC
debug.SetGCPercent(-1)          // disable

SetMemoryLimit (Go 1.19+)

debug.SetMemoryLimit(1 << 30) // 1 GiB soft limit

FreeOSMemory

debug.FreeOSMemory() // hint to return memory to the OS

Stack traces

Stack / PrintStack

defer func() {
    if r := recover(); r != nil {
        log.Printf("panic: %v\n%s", r, debug.Stack())
    }
}()

Build info

ReadBuildInfo

if info, ok := debug.ReadBuildInfo(); ok {
    fmt.Println(info.Main.Path, info.Main.Version)
    for _, s := range info.Settings {
        fmt.Println(s.Key, s.Value) // vcs.revision, vcs.time, ...
    }
}

Panic control

SetPanicOnFault / SetTraceback

debug.SetPanicOnFault(true)
debug.SetTraceback("all") // or "system", "crash"