/
profile.go
80 lines (74 loc) · 1.53 KB
/
profile.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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package helpers
import (
"fmt"
"github.com/bocajim/helpers/log"
"net/http"
_ "net/http/pprof"
"os"
"runtime/pprof"
"strconv"
"strings"
"time"
)
var activeCpuProfiling = false
var activeMemProfiling = false
var activeWebProfiling = false
func memProfileSaver(minuteInterval int, fileName string) {
i := 1
for {
select {
case <-time.After(time.Duration(minuteInterval) * time.Minute):
f, err := os.Create(fileName + fmt.Sprintf(".%d", i*minuteInterval))
if err != nil {
log.Printf(log.Warn, "Could not write memory profile: "+err.Error())
break
}
pprof.WriteHeapProfile(f)
log.Printf(log.Info, "Saved memory profile.")
i++
f.Close()
break
}
}
}
func ConfigureProfiling(config string) {
s := strings.Split(config, ",")
if len(s) >= 2 {
switch s[0] {
case "cpu", "CPU":
activeCpuProfiling = true
f, err := os.Create(s[1])
if err != nil {
log.Printf(log.Warn, "Could not initialize CPU profiler: "+err.Error())
break
}
pprof.StartCPUProfile(f)
break
case "mem", "MEM":
activeMemProfiling = true
interval := 10
if len(s) == 3 {
v, err := strconv.Atoi(s[2])
if err == nil {
interval = v
}
}
go memProfileSaver(interval, s[1])
break
case "web", "WEB":
activeWebProfiling = true
go func() {
err := http.ListenAndServe(s[1], nil)
if err != nil {
log.Printf(log.Warn, "Could not initialize debug web server: "+err.Error())
}
}()
break
}
}
}
func DeferredProfiling() {
if activeCpuProfiling {
pprof.StopCPUProfile()
}
}