Go runtime instrumentation library for collecting execution data from your applications.
go get github.com/runcfg/gostat/pkgpackage main
import (
"time"
runtime "github.com/runcfg/gostat/pkg"
)
func main() {
// Initialize gostat runtime collection
runtime.Init(runtime.Config{
OutputFile: "gostat-runtime.json",
SampleRate: 1.0,
TrackTime: true,
TrackMemory: true,
FlushInterval: 5 * time.Second,
})
defer runtime.Shutdown()
// Your application code...
processRequests()
}
func processRequests() {
defer runtime.Track("processRequests")()
// Function implementation...
}Initialize the runtime collector. Call this at the start of your main function.
Config options:
OutputFile- Path to write runtime data (default:"gostat-runtime.json")SampleRate- Fraction of calls to track, 0.0-1.0 (default:1.0)TrackTime- Enable execution time tracking (default:true)TrackMemory- Enable memory allocation tracking (default:true)FlushInterval- How often to write data to disk (default:5s)BufferSize- Max entries before forcing a flush (default:10000)
Track a function call by name. Use with defer:
func MyFunction() {
defer runtime.Track("MyFunction")()
// ... function body
}Automatically derive the function name from the call stack:
func MyFunction() {
defer runtime.TrackFunc()()
// ... function body
}Stop the collector and write final data to disk. Call with defer in main:
func main() {
runtime.Init(runtime.DefaultConfig())
defer runtime.Shutdown()
// ...
}Get current function statistics without writing to disk.
Immediately write current data to disk.
The runtime data is written as JSON with the following structure:
{
"version": "1.0",
"timestamp": "2024-01-15T10:30:00Z",
"collection_duration_ns": 60000000000,
"functions": {
"main.processRequests": {
"name": "main.processRequests",
"call_count": 1000,
"total_time_ns": 5000000000,
"min_time_ns": 1000000,
"max_time_ns": 50000000,
"avg_time_ns": 5000000,
"mem_alloc_bytes": 1024000
}
},
"call_graph": [
{
"caller": "main.main",
"callee": "main.processRequests",
"call_count": 1000
}
],
"memory_stats": {
"total_alloc_bytes": 10240000,
"heap_alloc_bytes": 5120000,
"heap_objects": 1000,
"num_gc": 5
}
}After collecting runtime data, analyze it with the gostat CLI:
# Generate HTML report with runtime data
gostat multi-analyze --html -o report.html ./project1 ./project2
# The report will automatically load gostat-runtime.json if presentThe runtime instrumentation is designed to be lightweight:
- Function tracking adds ~100ns per call
- Memory tracking adds ~500ns per call (can be disabled)
- Data is buffered and flushed periodically to minimize I/O impact
- Use
SampleRate < 1.0for high-frequency functions