/
pprof.go
41 lines (35 loc) · 919 Bytes
/
pprof.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package server
import (
"net/http"
"os"
"runtime/pprof"
)
func StartCpuProfiler(config *Config) (func(), error) {
empty := func() {}
if config.CpuProfile == "" {
return empty, nil
}
f, err := os.Create(config.CpuProfile)
if err != nil {
return empty, err
}
config.Logger.Info("starting CPU profiler", "profile", config.CpuProfile)
if err := pprof.StartCPUProfile(f); err != nil {
return empty, err
}
go func() {
config.Logger.Info("Starting pprof server", "addr", config.PprofRpc.Host)
err := http.ListenAndServe(config.PprofRpc.Host, nil)
config.Logger.Error("pprof server error", "err", err)
}()
return func() {
config.Logger.Info("stopping CPU profiler", "profile", config.CpuProfile)
pprof.StopCPUProfile()
if err := f.Close(); err != nil {
config.Logger.Info("failed to close cpu-profile file",
"profile", config.CpuProfile,
"err", err.Error(),
)
}
}, nil
}