-
Notifications
You must be signed in to change notification settings - Fork 15
/
trace.go
81 lines (69 loc) · 2.1 KB
/
trace.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
81
//go:build trace
package main
import (
"log"
"os"
"runtime"
"runtime/pprof"
"time"
"net/http"
_ "net/http/pprof"
"github.com/felixge/fgtrace"
"github.com/spf13/pflag"
)
var (
cpuProfileFilename string
memProfileFilename string
fgtraceFilename string
cpuProfileFile os.File
)
func init() {
pflag.StringVarP(&cpuProfileFilename, "cpuprofile", "u", "", "write CPU profile to `file`")
pflag.StringVarP(&memProfileFilename, "memprofile", "t", "", "write memory profile to `file`")
pflag.StringVarP(&fgtraceFilename, "fgtrace", "g", "", "write fgtrace to `file`")
// Start the pprof HTTP server as well
go func() {
log.Println("Starting pprof server at :6060")
log.Println("Try: http://localhost:6060/debug/pprof/goroutine?debug=2")
log.Println(http.ListenAndServe(":6060", nil))
}()
// Give it some time to be able to show the log messages from the goroutine above
time.Sleep(1200 * time.Millisecond)
}
func traceStart() {
// Output CPU profile information, if a filename is given
if cpuProfileFilename != "" {
cpuProfileFile, err := os.Create(cpuProfileFilename)
if err != nil {
log.Fatal("could not create CPU profile: ", err)
}
// Set the rate and start profiling the CPU usage
// runtime.SetCPUProfileRate(500)
if err := pprof.StartCPUProfile(cpuProfileFile); err != nil {
log.Fatal("could not start CPU profile: ", err)
}
}
if fgtraceFilename != "" {
defer fgtrace.Config{Dst: fgtrace.File(fgtraceFilename)}.Trace().Stop()
}
}
func traceComplete() {
// Output memory profile information, if a filename is given
if memProfileFilename != "" {
f, err := os.Create(memProfileFilename)
if err != nil {
log.Fatal("could not create memory profile: ", err)
logf("could not create memory profile: %v\n", err)
}
defer f.Close() // error handling omitted for example
runtime.GC() // get up-to-date statistics
if err := pprof.WriteHeapProfile(f); err != nil {
log.Fatal("could not write to memory profile: ", err)
logf("could not write to memory profile: %v\n", err)
}
}
if cpuProfileFilename != "" {
pprof.StopCPUProfile()
cpuProfileFile.Close()
}
}