prometheus.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. if len(conf.PrometheusBind) == 0 {
  19. return
  20. }
  21. prometheusRequestsTotal = prometheus.NewCounter(prometheus.CounterOpts{
  22. Name: "requests_total",
  23. Help: "A counter of the total number of HTTP requests imgproxy processed.",
  24. })
  25. prometheusErrorsTotal = prometheus.NewCounterVec(prometheus.CounterOpts{
  26. Name: "errors_total",
  27. Help: "A counter of the occured errors separated by type.",
  28. }, []string{"type"})
  29. prometheusRequestDuration = prometheus.NewHistogram(prometheus.HistogramOpts{
  30. Name: "request_duration_seconds",
  31. Help: "A histogram of the response latency.",
  32. })
  33. prometheusDownloadDuration = prometheus.NewHistogram(prometheus.HistogramOpts{
  34. Name: "download_duration_seconds",
  35. Help: "A histogram of the source image downloading latency.",
  36. })
  37. prometheusProcessingDuration = prometheus.NewHistogram(prometheus.HistogramOpts{
  38. Name: "processing_duration_seconds",
  39. Help: "A histogram of the image processing latency.",
  40. })
  41. prometheus.MustRegister(
  42. prometheusRequestsTotal,
  43. prometheusErrorsTotal,
  44. prometheusRequestDuration,
  45. prometheusDownloadDuration,
  46. prometheusProcessingDuration,
  47. )
  48. prometheusEnabled = true
  49. s := http.Server{
  50. Addr: conf.PrometheusBind,
  51. Handler: promhttp.Handler(),
  52. }
  53. go func() {
  54. log.Printf("Starting Prometheus server at %s\n", s.Addr)
  55. if err := s.ListenAndServe(); err != nil && err != http.ErrServerClosed {
  56. log.Fatalln(err)
  57. }
  58. }()
  59. }
  60. func startPrometheusDuration(m prometheus.Histogram) func() {
  61. t := time.Now()
  62. return func() {
  63. m.Observe(time.Since(t).Seconds())
  64. }
  65. }
  66. func incrementPrometheusErrorsTotal(t string) {
  67. prometheusErrorsTotal.With(prometheus.Labels{"type": t}).Inc()
  68. }