/
pprof.go
56 lines (53 loc) · 1.23 KB
/
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package micro
import (
"context"
"fmt"
"os"
"runtime/pprof"
"runtime/trace"
"time"
)
func Pprof(ctx context.Context, duration time.Duration) error {
if duration <= 5*time.Second || duration >= 10*time.Minute {
duration = 30 * time.Second
}
f, err := os.OpenFile("pprof.out", os.O_CREATE|os.O_TRUNC|os.O_RDWR, 0644)
if err != nil {
return err
}
defer f.Close()
if err := pprof.StartCPUProfile(f); err != nil {
return err
}
fmt.Fprintf(os.Stdout, "start cpu profile: %s\n", time.Now().Format(time.RFC3339))
defer pprof.StopCPUProfile()
defer func() {
fmt.Fprintf(os.Stdout, "Please use `go tool -http:0.0.0.0:80 pprof prof.out`")
}()
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(duration):
return nil
}
}
func Trace(ctx context.Context, duration time.Duration) error {
if duration <= 5*time.Second || duration >= 10*time.Minute {
duration = 30 * time.Second
}
f, err := os.OpenFile("trace.out", os.O_CREATE|os.O_TRUNC|os.O_RDWR, 0644)
if err != nil {
return err
}
trace.Start(f)
defer trace.Stop()
defer func() {
fmt.Fprintf(os.Stdout, "Please use `go tool -http:0.0.0.0:80 trace trace.out`")
}()
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(duration):
return nil
}
}