-
Notifications
You must be signed in to change notification settings - Fork 41
/
metrics.go
59 lines (47 loc) · 1.58 KB
/
metrics.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
package metrics
import (
"fmt"
"os"
"path/filepath"
"runtime/pprof"
"strconv"
"time"
"github.com/wakatime/wakatime-cli/pkg/ini"
"github.com/wakatime/wakatime-cli/pkg/log"
)
// StartProfiling starts profiling cpu and memory. It returns a function that
// should be called to stop profiling and close the files.
func StartProfiling() (func(), error) {
folder, err := ini.WakaResourcesDir()
if err != nil {
return nil, fmt.Errorf("failed getting user's home directory: %s", err)
}
metricsFolder := filepath.Join(folder, "metrics")
if err := os.MkdirAll(metricsFolder, 0750); err != nil {
return nil, fmt.Errorf("failed to create metrics folder: %s", err)
}
now := strconv.FormatInt(time.Now().UTC().UnixNano(), 10)
cpuf, err := os.Create(filepath.Join(metricsFolder, fmt.Sprintf("cpu_%s.profile", now))) // nolint:gosec
if err != nil {
return nil, fmt.Errorf("failed to create cpu profile file: %s", err)
}
if err := pprof.StartCPUProfile(cpuf); err != nil {
log.Errorf("failed to start cpu profile: %s", err)
}
memf, err := os.Create(filepath.Join(metricsFolder, fmt.Sprintf("mem_%s.profile", now))) // nolint:gosec
if err != nil {
return nil, fmt.Errorf("failed to create mem profile file: %s", err)
}
if err := pprof.WriteHeapProfile(memf); err != nil {
log.Errorf("failed to write heap profile: %s", err)
}
return func() {
pprof.StopCPUProfile()
if err := cpuf.Close(); err != nil {
log.Errorf("failed to close cpu profile file: %s", err)
}
if err := memf.Close(); err != nil {
log.Errorf("failed to close mem profile file: %s", err)
}
}, nil
}