How to log expvar statistics and metrics for analysis and debugging in Go?

To log expvar statistics and metrics for analysis and debugging in Go, follow these steps:

  1. Import the necessary packages:
import ( "expvar" "log" "net/http" )
  1. Create expvar variables that you want to track:
var ( counter = expvar.NewInt("counter") timer = expvar.NewFloat("timer") )
  1. Increment the counter and update the timer's value as needed:
counter.Add(1) timer.Set(3.14)
  1. Optionally, you can create custom expvar variables to track additional information. For example, if you have a struct with fields you want to expose, you can register it as an expvar:
type Custom struct { Field1 int Field2 string } custom := &Custom{Field1: 42, Field2: "hello"} expvar.Publish("custom", custom)
  1. Start the HTTP server to expose the expvar statistics:
expvarHandler := expvar.Handler() http.Handle("/debug/vars", expvarHandler) log.Fatal(http.ListenAndServe(":8080", nil))
  1. Now you can access the expvar statistics by visiting 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.