prometheus.go 2.1 KB

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