zdebug.go 1017 Bytes
Newer Older
Vladimir Barsukov's avatar
zdebug  
Vladimir Barsukov committed
1
2
3
4
5
package zdebug

import (
	"fmt"
	"git.barsukov.pro/barsukov/zgo/zjson"
Vladimir Barsukov's avatar
Vladimir Barsukov committed
6
	"git.barsukov.pro/barsukov/zgo/zutils"
Vladimir Barsukov's avatar
zdebug  
Vladimir Barsukov committed
7
	"runtime"
Vladimir Barsukov's avatar
Vladimir Barsukov committed
8
	"strings"
Vladimir Barsukov's avatar
zdebug  
Vladimir Barsukov committed
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
	"time"
)

type Monitor struct {
	Alloc,
	Sys,
	LiveObjects uint64

	NumGC        uint32
	NumGoroutine int
}

func NewMonitor(secs int) {
	go func() {
		var m Monitor
		var rtm runtime.MemStats
		var interval = time.Duration(secs) * time.Second
		for {
			<-time.After(interval)

			runtime.ReadMemStats(&rtm)

			m.NumGoroutine = runtime.NumGoroutine()

			m.Alloc = rtm.Alloc / 1e6
			m.Sys = rtm.Sys / 1e6
			m.LiveObjects = rtm.Mallocs - rtm.Frees
			m.NumGC = rtm.NumGC

			fmt.Println(zjson.MustString(m))
		}
	}()
}
Vladimir Barsukov's avatar
Vladimir Barsukov committed
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62

func Trace() []string {
	var out []string

	pc := make([]uintptr, 10)
	runtime.Callers(2, pc)

	for i := range pc {
		if f := runtime.FuncForPC(pc[i]); f != nil {
			file, line := f.FileLine(pc[i])

			if strings.Contains(file, "go/pkg") {
				continue
			}

			out = append(out, fmt.Sprintf("%s:%d", f.Name(), line))
		}
	}

	return zutils.ArrayUnique(out)
}