github.com/msales/pkg/v3@v3.24.0/clix/stats.go (about) 1 package clix 2 3 import ( 4 "fmt" 5 "net/http" 6 "net/url" 7 "time" 8 9 "github.com/msales/pkg/v3/log" 10 "github.com/msales/pkg/v3/stats" 11 "gopkg.in/urfave/cli.v1" 12 ) 13 14 // NewStats creates a new stats client. 15 func NewStats(c *cli.Context, l log.Logger) (stats.Stats, error) { 16 var s stats.Stats 17 var err error 18 19 dsn := c.String(FlagStatsDSN) 20 if dsn == "" { 21 return stats.Null, nil 22 } 23 24 uri, err := url.Parse(dsn) 25 if err != nil { 26 return nil, err 27 } 28 29 switch scheme := uri.Scheme; scheme { 30 case "statsd": 31 s, err = newStatsDStats(c, uri.Host) 32 if err != nil { 33 return nil, err 34 } 35 36 case "l2met": 37 s = newL2metStats(c, l) 38 39 case "prometheus": 40 s = newPrometheusStats(c, uri.Host, l) 41 42 default: 43 return nil, fmt.Errorf("Unknown scheme: %s", scheme) 44 } 45 46 tags, err := SplitTags(c.StringSlice(FlagStatsTags), "=") 47 if err != nil { 48 return nil, err 49 } 50 51 return stats.NewTaggedStats(s, tags...), nil 52 } 53 54 func newStatsDStats(c *cli.Context, addr string) (stats.Stats, error) { 55 s, err := stats.NewBufferedStatsd(addr, c.String(FlagStatsPrefix), stats.WithFlushInterval(1*time.Second)) 56 if err != nil { 57 return nil, err 58 } 59 60 return s, nil 61 } 62 63 func newL2metStats(c *cli.Context, l log.Logger) stats.Stats { 64 return stats.NewL2met(l, c.String(FlagStatsPrefix)) 65 } 66 67 func newPrometheusStats(c *cli.Context, addr string, l log.Logger) stats.Stats { 68 s := stats.NewPrometheus(c.String(FlagStatsPrefix)) 69 70 if addr != "" { 71 mux := http.NewServeMux() 72 mux.Handle("/metrics", s.Handler()) 73 go func() { 74 if err := http.ListenAndServe(addr, mux); err != nil { 75 l.Error(err.Error()) 76 } 77 }() 78 } 79 80 return s 81 }