rcrowley / go-metrics

Go port of Coda Hale's Metrics library
Other
3.43k stars 493 forks source link

Question - returning a copy of the metrics registry #203

Closed katzien closed 7 years ago

katzien commented 7 years ago

Hi there!

I'm writing a simple function that returns the DefaultRegistry for outputting it in JSON later on:

func (m *Handler) GetMetrics() interface{} {
    return metrics.DefaultRegistry
}

(The Handler is a wrapper around the metrics library in my app).

I'd like this function to return a deep copy of the metrics.DefaultRegistry though, not a pointer to the original metrics.DefaultRegistry as it seems to be doing currently.

I tried to use reflection and do something similar to this, but for some reason I seem to be getting a copy of a pointer which points to the original registry, rather than a complete copy of the registry itself which I can modify without changing the original DefaultRegistry.

I didn't see the metrics library itself providing a function that returns a copy of the registry, but maybe I missed something?

Would anyone be able to help or advise? Thanks in advance :)

katzien commented 7 years ago

I ended up just manually copying the registry:

// GetMetrics returns a copy of the metrics registry with all metrics
func (m *Handler) GetMetrics() interface{} {
    registryCopy := metrics.NewRegistry()
    metrics.DefaultRegistry.Each(func(name string, i interface{}) {
        registryCopy.Register(name, i)
    })

    return registryCopy
}

Probably not the most efficient way, but I couldn't make it work with reflection :)