Rafal G.
Rafal G.

Reputation: 4432

Method-level execution time metrics in Golang?

I am quite new to Go and I was wondering if there are any nice (like AOP in Java) ways to gather method-level execution time metrics in Go?

It would be best if such code would not be placed inside regular business logic code.

I don't want to profile an app. I mean real production ready metrics that could be exported to Graphite etc. so I could monitor response time histograms and such.

Upvotes: 3

Views: 2308

Answers (1)

Caleb
Caleb

Reputation: 9458

You could rewrite source code using the go parser and add the instructions. This is how godebug and the coverage tool work: https://github.com/mailgun/godebug.

Obviously that would be a lot of work, but I think your methodology is flawed anyway. Measuring everything means your program will spend far more time measuring than actually doing work. This is why profiling only samples.

It sounds like perhaps you're working on an HTTP project? You could easily instrument your code by wrapping all your http.Handlers or using a framework like Negroni. Here's an example of someone doing something similar. Go also has the expvar package which is sometimes useful for counters and the like.

Also worth considering is using a statsd client (which can get your data into Graphite). Here's one package which can do that: godspeed*. Calls are pretty easy:

package main

import (
    "fmt"
    "net/http"
    "time"

    "github.com/PagerDuty/godspeed"
    "github.com/codegangsta/negroni"
)

func statsdMiddleware(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
    start := time.Now()
    next(w, r)
    elapsed := float64(time.Now().Sub(start)) / float64(time.Millisecond)

    g, err := godspeed.NewDefault()
    if err != nil {
        return
    }
    defer g.Conn.Close()

    g.Histogram("http.response.time_ms", elapsed, []string{"path:" + r.URL.Path})
}

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
        fmt.Fprintf(w, "Welcome to the home page!")
    })

    n := negroni.Classic()
    n.Use(negroni.HandlerFunc(statsdMiddleware))
    n.UseHandler(mux)
    n.Run(":3000")
}

This approach works for standard TCP servers as well. For pipelines reading / writing queues I usually measure how fast I'm reading in data and writing it out the other end and then use back-pressure gauges for the intermediate steps. (which helps me find out which step is causing the problem)

Disclaimer: I work at DataDog

Upvotes: 1

Related Questions