RoadSign/pkg/navi/metrics.go

71 lines
1.5 KiB
Go
Raw Normal View History

2024-01-25 06:46:43 +00:00
package navi
import (
"bufio"
"os"
"time"
jsoniter "github.com/json-iterator/go"
"github.com/spf13/viper"
)
2024-01-25 06:46:43 +00:00
2024-01-31 05:17:52 +00:00
type RoadMetrics struct {
Traffic map[string]int64 `json:"traffic"`
TotalTraffic int64 `json:"total_traffic"`
StartupAt time.Time `json:"startup_at"`
2024-01-31 05:17:52 +00:00
}
2024-01-25 06:46:43 +00:00
type RoadTrace struct {
Timestamp time.Time `json:"timestamp"`
2024-01-25 06:46:43 +00:00
Region string `json:"region"`
Location string `json:"location"`
Destination string `json:"destination"`
Uri string `json:"uri"`
IpAddress string `json:"ip_address"`
UserAgent string `json:"user_agent"`
Error RoadTraceError `json:"error"`
}
type RoadTraceError struct {
IsNull bool `json:"is_null"`
Message string `json:"message"`
}
2024-01-31 05:17:52 +00:00
func (v *RoadMetrics) AddTrace(trace RoadTrace) {
2024-10-18 15:21:51 +00:00
if viper.GetBool("performance.low_memory") {
return
}
2024-01-31 05:17:52 +00:00
v.TotalTraffic++
trace.Timestamp = time.Now()
2024-01-31 05:17:52 +00:00
if _, ok := v.Traffic[trace.Region]; !ok {
v.Traffic[trace.Region] = 0
} else {
v.Traffic[trace.Region]++
}
raw, _ := jsoniter.Marshal(trace)
accessLogger.Println(string(raw))
}
2024-01-31 05:17:52 +00:00
func (v *RoadMetrics) ReadTrace() []RoadTrace {
fp := viper.GetString("logging.access")
file, err := os.Open(fp)
if err != nil {
return nil
2024-01-31 05:17:52 +00:00
}
defer file.Close()
var out []RoadTrace
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
var entry RoadTrace
if err := jsoniter.Unmarshal([]byte(line), &entry); err == nil {
out = append(out, entry)
}
2024-01-25 06:46:43 +00:00
}
return out
2024-01-25 06:46:43 +00:00
}