How to expose custom application-specific metrics with expvar in Go?

To expose custom application-specific metrics with expvar in Go, you can follow these steps:

  1. Start by importing the necessary packages:
import ( "expvar" "net/http" )
  1. Create a struct to hold your custom metrics:
type customMetrics struct { Counter expvar.Int Average expvar.Float }
  1. Initialize your custom metrics in the init() function:
func init() { expvar.Publish("CustomMetrics", expvar.Func(func() interface{} { return customMetrics{ Counter: expvar.NewInt("counter"), Average: expvar.NewFloat("average"), } })) }
  1. Increment and update your custom metrics whenever necessary:
// Increment counter metric customMetrics.Counter.Add(1) // Update average metric value := 10.5 customMetrics.Average.Update(value)

Note that the customMetrics struct is published as a JSON object under the /debug/vars endpoint. You can access it by visiting http://localhost:port/debug/vars in your browser.

  1. Finally, start an HTTP server to listen for requests:
func main() { http.ListenAndServe(":8080", nil) }

Now your custom metrics will be exposed alongside the default expvar metrics. You can use expvar for monitoring and exposing various metrics and runtime variables in your Go application.