starlog/metrics_test.go

100 lines
2.4 KiB
Go
Raw Permalink Normal View History

2026-03-19 16:37:57 +08:00
package starlog
import (
"sync/atomic"
"testing"
"time"
)
type metricsSink struct {
writes uint64
}
func (sink *metricsSink) Write(data []byte) error {
_ = data
atomic.AddUint64(&sink.writes, 1)
return nil
}
func (sink *metricsSink) Close() error {
return nil
}
func TestMetricsSnapshotIncludesPendingAndMultiSink(t *testing.T) {
logger := NewStarlog(nil)
logger.SetShowStd(false)
logger.SetShowColor(false)
logger.SetPendingWriteLimit(8)
logger.SetPendingDropPolicy(PendingDropOldest)
logger.SetSamplingConfig(SamplingConfig{
Enable: true,
Levels: []int{LvInfo},
Rate: 0.5,
Scope: SamplingScopeGlobal,
})
logger.SetDedupConfig(DedupConfig{
Enable: true,
Levels: []int{LvInfo},
Window: time.Second,
Scope: DedupScopeByKey,
})
multi := NewMultiSink(&metricsSink{})
logger.SetSink(multi)
logger.SetSwitching(true)
logger.Infoln("pending")
snapshot := logger.GetMetricsSnapshot()
if !snapshot.HasSink {
t.Fatalf("snapshot should report sink")
}
if !snapshot.HasMultiSink {
t.Fatalf("snapshot should report multi sink")
}
if len(snapshot.MultiSink.Sinks) != 1 {
t.Fatalf("snapshot multi sink stats should include one sink")
}
if snapshot.Pending.Length == 0 {
t.Fatalf("snapshot should include pending queue length")
}
if snapshot.Pending.Policy != PendingDropOldest {
t.Fatalf("snapshot should include pending policy")
}
if snapshot.Errors.WriteErrors != GetWriteErrorCount() {
t.Fatalf("snapshot write error count should match global counter")
}
if !snapshot.Sampling.Enabled || snapshot.Sampling.Rate != 0.5 {
t.Fatalf("snapshot should include sampling stats, got %+v", snapshot.Sampling)
}
if !snapshot.Dedup.Enabled || snapshot.Dedup.Window != time.Second {
t.Fatalf("snapshot should include dedup stats, got %+v", snapshot.Dedup)
}
logger.SetSwitching(false)
}
func TestGetAsyncMetrics(t *testing.T) {
StopStacks()
StartStacks()
metrics := GetAsyncMetrics()
if !metrics.Started {
t.Fatalf("async metrics should show started state")
}
if metrics.QueueCapacity == 0 {
t.Fatalf("async metrics should expose queue capacity")
}
StopStacks()
metrics = GetAsyncMetrics()
if metrics.Started {
t.Fatalf("async metrics should show stopped state after StopStacks")
}
}
func TestMetricsSnapshotNilLogger(t *testing.T) {
var logger *StarLogger
snapshot := logger.GetMetricsSnapshot()
if snapshot.Time.IsZero() {
t.Fatalf("snapshot should contain timestamp")
}
}