prometheus.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package main
  2. import (
  3. "log"
  4. "net/http"
  5. "time"
  6. "github.com/prometheus/client_golang/prometheus"
  7. "github.com/prometheus/client_golang/prometheus/promhttp"
  8. )
  9. var (
  10. prometheusEnabled = false
  11. prometheusRequestsTotal prometheus.Counter
  12. prometheusErrorsTotal *prometheus.CounterVec
  13. prometheusRequestDuration prometheus.Histogram
  14. prometheusDownloadDuration prometheus.Histogram
  15. prometheusProcessingDuration prometheus.Histogram
  16. )
  17. func initPrometheus() {
  18. prometheusRequestsTotal = prometheus.NewCounter(prometheus.CounterOpts{
  19. Name: "requests_total",
  20. Help: "A counter of the total number of HTTP requests imgproxy processed.",
  21. })
  22. prometheusErrorsTotal = prometheus.NewCounterVec(prometheus.CounterOpts{
  23. Name: "errors_total",
  24. Help: "A counter of the occured errors separated by type.",
  25. }, []string{"type"})
  26. prometheusRequestDuration = prometheus.NewHistogram(prometheus.HistogramOpts{
  27. Name: "request_duration_seconds",
  28. Help: "A histogram of the response latency.",
  29. })
  30. prometheusDownloadDuration = prometheus.NewHistogram(prometheus.HistogramOpts{
  31. Name: "download_duration_seconds",
  32. Help: "A histogram of the source image downloading latency.",
  33. })
  34. prometheusProcessingDuration = prometheus.NewHistogram(prometheus.HistogramOpts{
  35. Name: "processing_duration_seconds",
  36. Help: "A histogram of the image processing latency.",
  37. })
  38. prometheus.MustRegister(
  39. prometheusRequestsTotal,
  40. prometheusErrorsTotal,
  41. prometheusRequestDuration,
  42. prometheusDownloadDuration,
  43. prometheusProcessingDuration,
  44. )
  45. prometheusEnabled = true
  46. s := http.Server{
  47. Addr: conf.PrometheusBind,
  48. Handler: promhttp.Handler(),
  49. }
  50. go func() {
  51. log.Printf("Starting Prometheus server at %s\n", s.Addr)
  52. if err := s.ListenAndServe(); err != nil && err != http.ErrServerClosed {
  53. log.Fatalln(err)
  54. }
  55. }()
  56. }
  57. func startPrometheusDuration(m prometheus.Histogram) func() {
  58. t := time.Now()
  59. return func() {
  60. m.Observe(time.Since(t).Seconds())
  61. }
  62. }
  63. func incrementPrometheusErrorsTotal(t string) {
  64. prometheusErrorsTotal.With(prometheus.Labels{"type": t}).Inc()
  65. }