prom.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package service
  2. import (
  3. "context"
  4. "fmt"
  5. "time"
  6. "go-common/library/log"
  7. "go-common/library/stat/prom"
  8. )
  9. const (
  10. _timeFormat = "2006-01-02 15:04:05"
  11. )
  12. var (
  13. _names = make(map[string]struct{})
  14. _loc = time.Now().Location()
  15. )
  16. // IntervalConfig interval config.
  17. type IntervalConfig struct {
  18. Name string
  19. Rate int64
  20. }
  21. // Interval prom interval.
  22. type Interval struct {
  23. name string
  24. rate int64
  25. counter int64
  26. }
  27. // NewInterval new a interval instance.
  28. func NewInterval(c *IntervalConfig) *Interval {
  29. if _, ok := _names[c.Name]; ok {
  30. panic(fmt.Sprintf("%s already exists", c.Name))
  31. }
  32. _names[c.Name] = struct{}{}
  33. if c.Rate <= 0 {
  34. c.Rate = 1000
  35. }
  36. return &Interval{
  37. name: c.Name,
  38. rate: c.Rate,
  39. counter: 0,
  40. }
  41. }
  42. // MTS get mtime ts from mtime str with interval's counter.
  43. func (s *Interval) MTS(c context.Context, mtStr string) int64 {
  44. s.counter++
  45. if s.counter%s.rate == 0 {
  46. return 0
  47. }
  48. if mtStr == "" {
  49. return 0
  50. }
  51. t, err := time.ParseInLocation(_timeFormat, mtStr, _loc)
  52. if err != nil {
  53. log.Error("failed to parse mtime str for %s, time.ParseInLocation(%s, %s, %v) error(%v)", s.name, _timeFormat, mtStr, _loc, err)
  54. return 0
  55. }
  56. return t.Unix()
  57. }
  58. // Prom prom interval if mts > 0.
  59. func (s *Interval) Prom(c context.Context, mts int64) {
  60. if mts > 0 {
  61. prom.BusinessInfoCount.State(s.name, time.Now().Unix()-mts)
  62. }
  63. }