2022-10-29 11:15:39 +08: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"
|
|
|
|
"github.com/usememos/memos/store"
|
|
|
|
)
|
|
|
|
|
|
|
|
// MetricCollector is the metric collector.
|
|
|
|
type MetricCollector struct {
|
2022-11-26 09:23:38 +08:00
|
|
|
Collector metric.Collector
|
|
|
|
Enabled bool
|
|
|
|
Profile *profile.Profile
|
|
|
|
Store *store.Store
|
2022-10-29 11:15:39 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
const (
|
2022-11-12 09:02:44 +08:00
|
|
|
segmentMetricWriteKey = "fTn5BumOkj352n3TGw9tu0ARH2dOkcoQ"
|
2022-10-29 11:15:39 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
func NewMetricCollector(profile *profile.Profile, store *store.Store) MetricCollector {
|
|
|
|
c := segment.NewCollector(segmentMetricWriteKey)
|
|
|
|
|
|
|
|
return MetricCollector{
|
2022-11-26 09:23:38 +08:00
|
|
|
Collector: c,
|
|
|
|
Enabled: true,
|
|
|
|
Profile: profile,
|
|
|
|
Store: store,
|
2022-10-29 11:15:39 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (mc *MetricCollector) Collect(_ context.Context, metric *metric.Metric) {
|
2022-11-26 09:23:38 +08:00
|
|
|
if !mc.Enabled {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if mc.Profile.Mode == "dev" {
|
2022-10-29 11:15:39 +08:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if metric.Labels == nil {
|
|
|
|
metric.Labels = map[string]string{}
|
|
|
|
}
|
2022-11-26 09:23:38 +08:00
|
|
|
metric.Labels["version"] = version.GetCurrentVersion(mc.Profile.Mode)
|
2022-10-29 11:15:39 +08:00
|
|
|
|
2022-11-26 09:23:38 +08:00
|
|
|
err := mc.Collector.Collect(metric)
|
2022-10-29 11:15:39 +08:00
|
|
|
if err != nil {
|
|
|
|
fmt.Printf("Failed to request segment, error: %+v\n", err)
|
|
|
|
}
|
|
|
|
}
|