net/http/pprof
最後更新
net/http/pprof 把 Go 執行時的效能剖析資料(CPU、記憶體、goroutine 等)開成 HTTP 端點,讓你對執行中的服務做剖析。這個套件做什麼
程式變慢、記憶體一直漲、goroutine 越開越多時,你需要「剖析(profiling)」:看時間花在哪些函式、記憶體由誰配置。runtime/pprof 能把剖析資料寫成檔案,但長時間執行的伺服器不方便停下來改程式。
net/http/pprof 直接在 HTTP 伺服器上開一組 /debug/pprof/ 端點,需要時用瀏覽器或 go tool pprof 連上去抓資料即可。| 端點 | 內容 |
|---|---|
| /debug/pprof/ | 索引頁,列出所有剖析類型 |
/debug/pprof/profile?seconds=N | CPU 剖析,取樣 N 秒(預設 30) |
| /debug/pprof/heap | 記憶體(目前存活的配置) |
| /debug/pprof/allocs | 所有記憶體配置 |
| /debug/pprof/goroutine | 所有 goroutine 的呼叫堆疊 |
| /debug/pprof/block、/debug/pprof/mutex | 阻塞與鎖競爭(需先開啟取樣率) |
/debug/pprof/trace?seconds=N | 執行追蹤,給 go tool trace 用 |
拿到資料後的分析方法(
go tool pprof、火焰圖)見 pprof 效能剖析。注意:這些端點會洩漏程式內部資訊,CPU 剖析還會增加負載。不要對外公開,只聽
localhost 或放在需要驗證的內部 port。匯入
- import _ "net/http/pprof"
只需要它「註冊端點」的副作用時,用空白識別字
_ 匯入。要自己掛到其他路由器上,則正常匯入 "net/http/pprof"。常用 API
匿名匯入:註冊到 DefaultServeMux
import _ "net/http/pprof" 會在 init 時把端點註冊到 http.DefaultServeMux。只要你的程式用 http.ListenAndServe(addr, nil)(nil 代表使用 DefaultServeMux)啟動伺服器,端點就自動存在。常見寫法是另外開一個只聽本機的 goroutine:- go func() {
- log.Println(http.ListenAndServe("localhost:6060", nil))
- }()
Go 1.22 起,這些端點只接受 GET(以及 HEAD),其他方法會得到 405。
簽名:
- import _ "net/http/pprof"
範例用
httptest 把 DefaultServeMux 開在本機隨機 port,檢查索引頁列出的剖析類型。範例:
- package main
- import (
- "fmt"
- "io"
- "net/http"
- "net/http/httptest"
- _ "net/http/pprof"
- "strings"
- )
- func main() {
- srv := httptest.NewServer(http.DefaultServeMux)
- defer srv.Close()
- resp, err := http.Get(srv.URL + "/debug/pprof/")
- if err != nil {
- fmt.Println(err)
- return
- }
- body, _ := io.ReadAll(resp.Body)
- resp.Body.Close()
- fmt.Println(resp.StatusCode, resp.Header.Get("Content-Type"))
- for _, name := range []string{"allocs", "goroutine", "heap", "profile", "trace"} {
- fmt.Printf("%s listed: %v\n", name, strings.Contains(string(body), name))
- }
- resp, err = http.Post(srv.URL+"/debug/pprof/heap", "text/plain", nil)
- if err != nil {
- fmt.Println(err)
- return
- }
- resp.Body.Close()
- fmt.Println("POST:", resp.StatusCode)
- }
輸出:
- 200 text/html; charset=utf-8
- allocs listed: true
- goroutine listed: true
- heap listed: true
- profile listed: true
- trace listed: true
- POST: 405
掛到自己的 ServeMux:Index、Cmdline、Profile、Symbol、Trace
如果你的應用程式用的是自己建立的
http.NewServeMux(),匿名匯入註冊在 DefaultServeMux 上的端點不會出現在你的路由裡。這其實是好事:可以把剖析端點放在另一個只聽本機的伺服器,和對外的應用程式分開。手動註冊時要掛五個函式。
Index 註冊在 /debug/pprof/ 子樹,它除了顯示索引頁,也負責 heap、goroutine 等具名剖析。簽名:
- func Index(w http.ResponseWriter, r *http.Request)
- func Cmdline(w http.ResponseWriter, r *http.Request)
- func Profile(w http.ResponseWriter, r *http.Request)
- func Symbol(w http.ResponseWriter, r *http.Request)
- func Trace(w http.ResponseWriter, r *http.Request)
範例中對外的
app 沒有剖析端點,回 404;debug 伺服器才有。範例:
- package main
- import (
- "fmt"
- "io"
- "net/http"
- "net/http/httptest"
- "net/http/pprof"
- )
- func main() {
- debug := http.NewServeMux()
- debug.HandleFunc("GET /debug/pprof/", pprof.Index)
- debug.HandleFunc("GET /debug/pprof/cmdline", pprof.Cmdline)
- debug.HandleFunc("GET /debug/pprof/profile", pprof.Profile)
- debug.HandleFunc("GET /debug/pprof/symbol", pprof.Symbol)
- debug.HandleFunc("GET /debug/pprof/trace", pprof.Trace)
- app := http.NewServeMux()
- app.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) {
- fmt.Fprint(w, "app")
- })
- appSrv := httptest.NewServer(app)
- defer appSrv.Close()
- debugSrv := httptest.NewServer(debug)
- defer debugSrv.Close()
- for _, u := range []string{appSrv.URL + "/debug/pprof/", debugSrv.URL + "/debug/pprof/"} {
- resp, err := http.Get(u)
- if err != nil {
- fmt.Println(err)
- continue
- }
- io.Copy(io.Discard, resp.Body)
- resp.Body.Close()
- fmt.Println(resp.StatusCode)
- }
- }
輸出:
- 404
- 200
pprof.Handler:只開放特定剖析
Handler(name) 回傳單一剖析類型的 Handler,名稱就是 runtime/pprof 的剖析名稱,例如 "goroutine"、"heap"、"allocs"、"block"、"mutex"。適合只想開放其中幾項,或想掛在自訂路徑時。查詢參數
debug=1 回傳人類可讀的文字格式;不加則是 go tool pprof 使用的二進位格式(gzip 壓縮的 protobuf)。簽名:
- func Handler(name string) http.Handler
範例只檢查第一行開頭,因為 goroutine 數量每次執行可能不同。
範例:
- package main
- import (
- "bufio"
- "fmt"
- "net/http"
- "net/http/httptest"
- "net/http/pprof"
- "strings"
- )
- func main() {
- mux := http.NewServeMux()
- mux.Handle("GET /debug/goroutines", pprof.Handler("goroutine"))
- mux.Handle("GET /debug/heap", pprof.Handler("heap"))
- srv := httptest.NewServer(mux)
- defer srv.Close()
- resp, err := http.Get(srv.URL + "/debug/goroutines?debug=1")
- if err != nil {
- fmt.Println(err)
- return
- }
- first, _ := bufio.NewReader(resp.Body).ReadString('\n')
- resp.Body.Close()
- fmt.Println(resp.StatusCode, strings.HasPrefix(first, "goroutine profile: total"))
- resp, err = http.Get(srv.URL + "/debug/heap")
- if err != nil {
- fmt.Println(err)
- return
- }
- resp.Body.Close()
- fmt.Println(resp.StatusCode, resp.Header.Get("Content-Type"))
- }
輸出:
- 200 true
- 200 application/octet-stream
Profile:CPU 剖析
Profile 在收到請求後開始 CPU 取樣,持續 seconds 參數指定的秒數(預設 30 秒),結束後回傳 gzip 壓縮的剖析資料。取樣期間請求會一直等著,所以用戶端的逾時要比 seconds 長。實務上直接用指令抓:- go tool pprof http://localhost:6060/debug/pprof/profile?seconds=30
簽名:
- func Profile(w http.ResponseWriter, r *http.Request)
範例讓一個 goroutine 忙碌地跑迴圈,抓 1 秒的 CPU 剖析,只檢查回應是否為 gzip 格式(開頭兩個位元組為
1f 8b)。注意:同一時間只能進行一個 CPU 剖析,重複請求會失敗。
範例:
- package main
- import (
- "fmt"
- "io"
- "net/http"
- "net/http/httptest"
- "net/http/pprof"
- )
- func busy(stop <-chan struct{}) {
- x := 0
- for {
- select {
- case <-stop:
- return
- default:
- x++
- }
- }
- }
- func main() {
- mux := http.NewServeMux()
- mux.HandleFunc("/debug/pprof/profile", pprof.Profile)
- srv := httptest.NewServer(mux)
- defer srv.Close()
- stop := make(chan struct{})
- go busy(stop)
- resp, err := http.Get(srv.URL + "/debug/pprof/profile?seconds=1")
- close(stop)
- if err != nil {
- fmt.Println(err)
- return
- }
- data, _ := io.ReadAll(resp.Body)
- resp.Body.Close()
- fmt.Println(resp.StatusCode, resp.Header.Get("Content-Type"))
- fmt.Println("gzip magic:", len(data) > 2 && data[0] == 0x1f && data[1] == 0x8b)
- }
輸出:
- 200 application/octet-stream
- gzip magic: true
Trace:執行追蹤
Trace 記錄 seconds 秒內的排程、系統呼叫、GC 等事件,產生的檔案用 go tool trace 開啟,可以看到每個 goroutine 何時在哪個執行緒上執行。seconds 可以是小數。- curl -o trace.out "http://localhost:6060/debug/pprof/trace?seconds=5"
- go tool trace trace.out
簽名:
- func Trace(w http.ResponseWriter, r *http.Request)
範例:
- package main
- import (
- "fmt"
- "io"
- "net/http"
- "net/http/httptest"
- "net/http/pprof"
- )
- func main() {
- mux := http.NewServeMux()
- mux.HandleFunc("/debug/pprof/trace", pprof.Trace)
- srv := httptest.NewServer(mux)
- defer srv.Close()
- resp, err := http.Get(srv.URL + "/debug/pprof/trace?seconds=0.2")
- if err != nil {
- fmt.Println(err)
- return
- }
- data, _ := io.ReadAll(resp.Body)
- resp.Body.Close()
- fmt.Println(resp.StatusCode, resp.Header.Get("Content-Type"), len(data) > 0)
- }
輸出:
- 200 application/octet-stream true
重點整理
import _ "net/http/pprof"會把 /debug/pprof/ 端點註冊到DefaultServeMux- 用自己的
ServeMux時,手動掛Index、Cmdline、Profile、Symbol、Trace - 剖析端點只開在本機或內部 port,不要對外公開
?debug=1取得文字格式;二進位格式交給go tool pprof- CPU 剖析與 trace 會等待
seconds秒,用戶端逾時要設得夠長