go语言监控(内部使用)

一、pprof

package main
import (
"math/rand"
"testing"
)

func BenchmarkRandom(b *testing.B) {
for i := 0; i < b.N; i++ {
    random()
}
}

func random() int {
return rand.Intn(100)
}

go test -c go_test.go
$ ./main.test -test.bench=. -test.cpuprofile=cpu-profile.prof
$ go tool pprof main.test cpu-profile.prof
(pprof) top 5

利用这个命令查看堆栈信息:

go tool pprof http://localhost:6060/debug/pprof/heap

利用这个命令可以查看程序CPU使用情况信息:

go tool pprof http://localhost:6060/debug/pprof/profile

使用这个命令可以查看block信息:

go tool pprof http://localhost:6060/debug/pprof/block

例如:

1)go tool pprof http://localhost:6060/debug/pprof/profile
2)top10
3)web 需要浏览器支持
go语言监控(内部使用)_第1张图片
top10.png
各字段含义:
  1. 采样点落在该函数中的次数
  2. 采样点落在该函数中的百分比
  3. 上一项的累积百分比
  4. 采样点落在该函数,以及被它调用的函数中的总次数
  5. 采样点落在该函数,以及被它调用的函数中的总次数百分比
  6. 函数名

设置采样率

go tool pprof --seconds 25 http://localhost:9090/debug/pprof/profile

生成svg文件

先安装sudo apt-get install graphviz(绘图工具)
go tool pprof -alloc_space -cum -svg http://127.0.0.1:8080/debug/pprof/heap > heap.svg
svg文件可以直接通过浏览器打开

go语言监控(内部使用)_第2张图片
矢量图.png

二、go + FlameGraph

go-torch是Uber公司开源的一款针对Golang程序的火焰图生成工具,能收集 stack traces,并把它们整理成火焰图,直观地程序给开发人员。go-torch是基于使用BrendanGregg创建的火焰图工具生成直观的图像,很方便地分析Go的各个方法所占用的CPU的时间。

1) 下载安装go-torch

go get github.com/uber/go-torch 编译生成二进制,放入bin下

2)下载火焰图工具

git clone https://github.com/brendangregg/FlameGraph.git

3)目录拷贝

cp flamegraph.pl /usr/local/bin

4) 采样抓取pprof数据

go-torch -u http://localhost:6060 -t 10
Writing svg to torch.svg

你可能感兴趣的:(go语言监控(内部使用))