Created
January 22, 2018 00:17
-
-
Save DazWilkin/a621b5ad96b1f75fbadf4244fd55e59d to your computer and use it in GitHub Desktop.
OpenCensus Golang Prometheus sample
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "context" | |
| "html/template" | |
| "log" | |
| "math/rand" | |
| "net/http" | |
| "time" | |
| "go.opencensus.io/exporter/stats/prometheus" | |
| "go.opencensus.io/stats" | |
| ) | |
| const ( | |
| html = `<!doctype html><html><body><a href="/metrics">metrics</a></body></html>` | |
| ) | |
| func main() { | |
| ctx := context.Background() | |
| exporter, err := prometheus.NewExporter(prometheus.Options{}) | |
| if err != nil { | |
| log.Fatal(err) | |
| } | |
| stats.RegisterExporter(exporter) | |
| videoSize, err := stats.NewMeasureInt64("my.org/measures/video_size_cum", "size of processed video", "MBy") | |
| if err != nil { | |
| log.Fatalf("Video size measure not created: %v", err) | |
| } | |
| viewSize, err := stats.NewView( | |
| "video_cum", | |
| "processed video size over time", | |
| nil, | |
| videoSize, | |
| stats.DistributionAggregation([]float64{0, 1 << 16, 1 << 32}), | |
| stats.Cumulative{}, | |
| ) | |
| if err != nil { | |
| log.Fatalf("Cannot create view: %v", err) | |
| } | |
| if err := viewSize.Subscribe(); err != nil { | |
| log.Fatalf("Cannot subscribe to the view: %v", err) | |
| } | |
| stats.SetReportingPeriod(1 * time.Second) | |
| go func() { | |
| for { | |
| stats.Record(ctx, videoSize.M(rand.Int63())) | |
| <-time.After(time.Millisecond * time.Duration(1+rand.Intn(400))) | |
| } | |
| }() | |
| addr := ":9999" | |
| log.Printf("Serving at %s", addr) | |
| http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { | |
| t, err := template.New("foo").Parse(html) | |
| if err != nil { | |
| log.Fatalf("Cannot parse template: %v", err) | |
| } | |
| t.Execute(w, "") | |
| }) | |
| http.Handle("/metrics", exporter) | |
| log.Fatal(http.ListenAndServe(addr, nil)) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment