forked from asonawalla/gazette
/
runtime.go
43 lines (36 loc) · 1000 Bytes
/
runtime.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
package mainboilerplate
import (
"fmt"
"io"
"os"
"runtime/pprof"
"time"
log "github.com/sirupsen/logrus"
)
// dump writes the heap and goroutine trace to |w|.
func dump(w io.Writer) {
pprof.Lookup("heap").WriteTo(w, 1)
pprof.Lookup("goroutine").WriteTo(w, 1)
}
// profileFile is the target file for CPU profiling.
var profileFile *os.File
// toggleProfiler starts and stops a long-running CPU profile using pprof. The
// profile is written to /var/tmp/profile_${PID}_${TIMESTAMP}.pprof where
// TIMESTAMP represents the epoch time when the profiling session began.
func toggleProfiler() {
if profileFile == nil {
var err error
filename := fmt.Sprintf("/var/tmp/profile_%d_%d.pprof",
os.Getpid(), time.Now().Unix())
profileFile, err = os.Create(filename)
if err == nil {
pprof.StartCPUProfile(profileFile)
} else {
log.WithField("err", err).Error("could not begin CPU profiling")
}
} else {
pprof.StopCPUProfile()
profileFile.Close()
profileFile = nil
}
}