wttr.in/internal/stats/stats.go

90 lines
1.8 KiB
Go
Raw Permalink Normal View History

2022-12-03 14:39:34 +00:00
package stats
2020-05-30 16:14:17 +00:00
2022-11-27 21:16:32 +00:00
import (
"bytes"
"fmt"
"net/http"
"sync"
"time"
2022-11-29 20:24:53 +00:00
"github.com/chubin/wttr.in/internal/routing"
2022-11-27 21:16:32 +00:00
)
// Stats holds processed requests statistics.
type Stats struct {
m sync.Mutex
v map[string]int
startTime time.Time
}
2022-12-03 14:39:34 +00:00
// New returns new Stats.
func New() *Stats {
2022-11-27 21:16:32 +00:00
return &Stats{
v: map[string]int{},
startTime: time.Now(),
}
}
// Inc key by one.
func (c *Stats) Inc(key string) {
c.m.Lock()
c.v[key]++
c.m.Unlock()
}
// Get current key counter value.
func (c *Stats) Get(key string) int {
c.m.Lock()
defer c.m.Unlock()
2022-12-11 13:28:34 +00:00
2022-11-27 21:16:32 +00:00
return c.v[key]
}
// Reset key counter.
func (c *Stats) Reset(key string) int {
c.m.Lock()
defer c.m.Unlock()
result := c.v[key]
c.v[key] = 0
2022-12-11 13:28:34 +00:00
2022-11-27 21:16:32 +00:00
return result
}
// Show returns current statistics formatted as []byte.
func (c *Stats) Show() []byte {
2022-12-11 13:28:34 +00:00
var b bytes.Buffer
2022-11-27 21:16:32 +00:00
c.m.Lock()
defer c.m.Unlock()
uptime := time.Since(c.startTime) / time.Second
fmt.Fprintf(&b, "%-20s: %v\n", "Running since", c.startTime.Format(time.RFC3339))
fmt.Fprintf(&b, "%-20s: %d\n", "Uptime (min)", uptime/60)
fmt.Fprintf(&b, "%-20s: %d\n", "Total queries", c.v["total"])
2022-12-11 13:28:34 +00:00
2022-11-27 21:16:32 +00:00
if uptime != 0 {
fmt.Fprintf(&b, "%-20s: %d\n", "Throughput (QpM)", c.v["total"]*60/int(uptime))
}
fmt.Fprintf(&b, "%-20s: %d\n", "Cache L1 queries", c.v["cache1"])
2022-12-11 13:28:34 +00:00
2022-11-27 21:16:32 +00:00
if c.v["total"] != 0 {
fmt.Fprintf(&b, "%-20s: %d\n", "Cache L1 queries (%)", (100*c.v["cache1"])/c.v["total"])
}
fmt.Fprintf(&b, "%-20s: %d\n", "Upstream queries", c.v["total"]-c.v["cache1"])
fmt.Fprintf(&b, "%-20s: %d\n", "Queries with format", c.v["format"])
fmt.Fprintf(&b, "%-20s: %d\n", "Queries with format=j1", c.v["format=j1"])
2022-12-04 15:55:14 +00:00
fmt.Fprintf(&b, "%-20s: %d\n", "Queries with known IP", c.v["geoip"])
2022-11-27 21:16:32 +00:00
return b.Bytes()
}
2022-11-29 20:24:53 +00:00
func (c *Stats) Response(*http.Request) *routing.Cadre {
return &routing.Cadre{
Body: c.Show(),
2022-11-27 21:16:32 +00:00
}
}