StartMemStats logs runtime.MemStats periodically until ctx is done. Call with a background goroutine when pprof is enabled for ongoing memory monitoring.
(ctx context.Context, log *slog.Logger, intervalSec int)
| 11 | // StartMemStats logs runtime.MemStats periodically until ctx is done. |
| 12 | // Call with a background goroutine when pprof is enabled for ongoing memory monitoring. |
| 13 | func StartMemStats(ctx context.Context, log *slog.Logger, intervalSec int) { |
| 14 | if intervalSec <= 0 { |
| 15 | intervalSec = 60 |
| 16 | } |
| 17 | ticker := time.NewTicker(time.Duration(intervalSec) * time.Second) |
| 18 | defer ticker.Stop() |
| 19 | |
| 20 | for { |
| 21 | select { |
| 22 | case <-ctx.Done(): |
| 23 | return |
| 24 | case <-ticker.C: |
| 25 | var m runtime.MemStats |
| 26 | runtime.ReadMemStats(&m) |
| 27 | log.Info("memstats", |
| 28 | "alloc_mb", m.Alloc/1024/1024, |
| 29 | "total_alloc_mb", m.TotalAlloc/1024/1024, |
| 30 | "sys_mb", m.Sys/1024/1024, |
| 31 | "num_gc", m.NumGC, |
| 32 | "heap_alloc_mb", m.HeapAlloc/1024/1024, |
| 33 | "heap_sys_mb", m.HeapSys/1024/1024, |
| 34 | ) |
| 35 | } |
| 36 | } |
| 37 | } |