用google/gops診斷Golang程式

myml發表於2017-03-04

在github上發現一個有趣的程式。 google/gops可以列出本機正在執行的Go程式,並診斷程式,可以檢視程式的堆疊,執行時等資訊 只需要在程式里加入github.com/google/gops/agent包,一個簡單的例子

// gopsTest project main.go
package main

import (
    "log"
    "time"

    "github.com/google/gops/agent"
)

func main() {
    if err := agent.Listen(&agent.Options{}); err != nil {
        log.Fatal(err)
    }
    time.Sleep(time.Hour)
}
➜  bin gops
8548    gops    (/home/myml/src/go/bin/gops)
8302*   gopsTest    (/tmp/gopsTest)
➜  bin gops memstats 8302
alloc: 194.63KB (199304 bytes)
total-alloc: 194.63KB (199304 bytes)
sys: 1.66MB (1740800 bytes)
lookups: 9
mallocs: 1182
frees: 67
heap-alloc: 194.63KB (199304 bytes)
heap-sys: 704.00KB (720896 bytes)
heap-idle: 136.00KB (139264 bytes)
heap-in-use: 568.00KB (581632 bytes)
heap-released: 0 bytes
heap-objects: 1115
stack-in-use: 320.00KB (327680 bytes)
stack-sys: 320.00KB (327680 bytes)
next-gc: when heap-alloc >= 4.27MB (4473924 bytes)
last-gc: -
gc-pause: 0s
num-gc: 0
enable-gc: true
debug-gc: false

也可以遠端診斷

➜  bin gops stats 127.0.0.1:41861
goroutines: 6
OS threads: 9
GOMAXPROCS: 4
num CPU: 4

更多的命令

Usage: gops is a tool to list and diagnose Go processes.

Commands:
    stack       Prints the stack trace.
    gc          Runs the garbage collector and blocks until successful.
    memstats    Prints the allocation and garbage collection stats.
    version     Prints the Go version used to build the program.
    stats       Prints the vital runtime stats.
    help        Prints this help text.

Profiling commands:
    trace       Runs the runtime tracer for 5 secs and launches "go tool trace".
    pprof-heap  Reads the heap profile and launches "go tool pprof".
    pprof-cpu   Reads the CPU profile and launches "go tool pprof".

All commands require the agent running on the Go process.
Symbol "*" indicates the process runs the agent.

相關文章