github.com/blend/go-sdk@v1.20220411.3/stats/runtime.go (about)

     1  /*
     2  
     3  Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file.
     5  
     6  */
     7  
     8  package stats
     9  
    10  import (
    11  	"runtime"
    12  	"time"
    13  )
    14  
    15  // Runtime reports golang vm runtime stats.
    16  func Runtime(collector Collector) {
    17  	if collector == nil {
    18  		return
    19  	}
    20  
    21  	go func() {
    22  		var previous, current runtime.MemStats
    23  		runtimeCollect(collector, &previous, &current)
    24  		for {
    25  			<-time.After(250 * time.Millisecond)
    26  			runtimeCollect(collector, &previous, &current)
    27  		}
    28  	}()
    29  }
    30  
    31  func runtimeCollect(collector Collector, previous, current *runtime.MemStats) {
    32  	runtime.ReadMemStats(current)
    33  
    34  	// these depend on the previous values
    35  	_ = collector.Gauge("go.runtime.mem.num_gc", float64(current.NumGC-previous.NumGC))
    36  	_ = collector.Gauge("go.runtime.mem.num_forced_gc", float64(current.NumForcedGC-previous.NumForcedGC))
    37  	_ = collector.Gauge("go.runtime.mem.pause_total_ns", float64(current.PauseTotalNs-previous.PauseTotalNs))
    38  	_ = collector.Gauge("go.runtime.mem.frees", float64(current.Frees-previous.Frees))
    39  	_ = collector.Gauge("go.runtime.mem.mallocs", float64(current.Mallocs-previous.Mallocs))
    40  
    41  	// these are mostly points in time.
    42  	_ = collector.Gauge("go.runtime.num_cpu", float64(runtime.NumCPU()))
    43  	_ = collector.Gauge("go.runtime.num_goroutine", float64(runtime.NumGoroutine()))
    44  
    45  	_ = collector.Gauge("go.runtime.mem.alloc", float64(current.Alloc))
    46  
    47  	_ = collector.Gauge("go.runtime.mem.gc_sys", float64(current.GCSys))
    48  	_ = collector.Gauge("go.runtime.mem.other_sys", float64(current.OtherSys))
    49  
    50  	_ = collector.Gauge("go.runtime.mem.heap_alloc", float64(current.HeapAlloc))
    51  	_ = collector.Gauge("go.runtime.mem.heap_idle", float64(current.HeapIdle))
    52  	_ = collector.Gauge("go.runtime.mem.heap_inuse", float64(current.HeapInuse))
    53  	_ = collector.Gauge("go.runtime.mem.heap_objects", float64(current.HeapObjects))
    54  	_ = collector.Gauge("go.runtime.mem.heap_sys", float64(current.HeapSys))
    55  
    56  	_ = collector.Gauge("go.runtime.mem.stack_inuse", float64(current.StackInuse))
    57  	_ = collector.Gauge("go.runtime.mem.stack_sys", float64(current.StackSys))
    58  	_ = collector.Gauge("go.runtime.mem.sys", float64(current.Sys))
    59  	_ = collector.Gauge("go.runtime.mem.total_alloc", float64(current.TotalAlloc))
    60  
    61  	// rotate the results ...
    62  	*previous = *current
    63  }