To log expvar statistics and metrics for analysis and debugging in Go, follow these steps:
import (
"expvar"
"log"
"net/http"
)
var (
counter = expvar.NewInt("counter")
timer = expvar.NewFloat("timer")
)
counter.Add(1)
timer.Set(3.14)
type Custom struct {
Field1 int
Field2 string
}
custom := &Custom{Field1: 42, Field2: "hello"}
expvar.Publish("custom", custom)
expvarHandler := expvar.Handler()
http.Handle("/debug/vars", expvarHandler)
log.Fatal(http.ListenAndServe(":8080", nil))
http://localhost:8080/debug/vars
in your web browser. This endpoint provides a JSON representation of all the exposed expvar variables.By logging these statistics and metrics, you can analyze them over time to identify performance bottlenecks or other issues in your Go application.