memos/server/metric_collector.go

63 lines
1.3 KiB
Go
Raw Normal View History

2022-10-29 06:15:39 +03:00
package server
import (
"context"
"fmt"
metric "github.com/usememos/memos/plugin/metrics"
"github.com/usememos/memos/plugin/metrics/segment"
"github.com/usememos/memos/server/profile"
"github.com/usememos/memos/server/version"
)
// MetricCollector is the metric collector.
type MetricCollector struct {
2023-01-05 15:56:50 +03:00
collector metric.Collector
ID string
Enabled bool
Profile *profile.Profile
2022-10-29 06:15:39 +03:00
}
const (
2023-01-05 15:56:50 +03:00
segmentMetricWriteKey = "NbPruMMmfqfD2AMCw3pkxZTsszVS3hKq"
2022-10-29 06:15:39 +03:00
)
2023-01-05 15:56:50 +03:00
func (s *Server) registerMetricCollector() {
2022-10-29 06:15:39 +03:00
c := segment.NewCollector(segmentMetricWriteKey)
2023-01-05 15:56:50 +03:00
mc := &MetricCollector{
collector: c,
ID: s.ID,
Enabled: false,
2023-01-05 15:56:50 +03:00
Profile: s.Profile,
2022-10-29 06:15:39 +03:00
}
2023-01-05 15:56:50 +03:00
s.Collector = mc
2022-10-29 06:15:39 +03:00
}
2023-01-05 15:56:50 +03:00
func (mc *MetricCollector) Identify(_ context.Context) {
if !mc.Enabled {
return
}
2023-01-05 15:56:50 +03:00
err := mc.collector.Identify(mc.ID)
if err != nil {
fmt.Printf("Failed to request segment, error: %+v\n", err)
}
}
func (mc *MetricCollector) Collect(_ context.Context, metric *metric.Metric) {
if !mc.Enabled {
2022-10-29 06:15:39 +03:00
return
}
if metric.Labels == nil {
metric.Labels = map[string]string{}
}
2023-01-05 15:56:50 +03:00
metric.Labels["mode"] = mc.Profile.Mode
metric.Labels["version"] = version.GetCurrentVersion(mc.Profile.Mode)
2023-01-05 15:56:50 +03:00
metric.ID = mc.ID
err := mc.collector.Collect(metric)
2022-10-29 06:15:39 +03:00
if err != nil {
fmt.Printf("Failed to request segment, error: %+v\n", err)
}
}