@@ -6,8 +6,8 @@ package monitoring
66import (
77 "context"
88 "log/slog"
9+ "path"
910 "runtime"
10- "strings"
1111 "sync"
1212
1313 "github.com/prometheus/client_golang/prometheus"
@@ -19,10 +19,6 @@ import (
1919// this map grows to a fixed size and all subsequent lookups are lock-free reads.
2020var pcFileCache sync.Map // uintptr -> string
2121
22- // modulePath is the Go module prefix stripped from caller file paths to produce
23- // relative paths suitable for use as Prometheus label values.
24- const modulePath = "github.com/cobaltcore-dev/cortex/"
25-
2622// LogMessagesTotal counts warn and error log messages emitted by both the slog
2723// and zap loggers. Labels: "level" (warn|error), "file" (relative source path).
2824var LogMessagesTotal = prometheus .NewCounterVec (prometheus.CounterOpts {
@@ -31,13 +27,16 @@ var LogMessagesTotal = prometheus.NewCounterVec(prometheus.CounterOpts{
3127 Help : "Total number of log messages emitted at warn or error level." ,
3228}, []string {"level" , "file" })
3329
34- // trimModulePrefix strips the Go module path prefix so that the file label
35- // contains only the project-relative path (e.g. "internal/scheduling/...").
36- func trimModulePrefix (file string ) string {
37- if i := strings .Index (file , modulePath ); i >= 0 {
38- return file [i + len (modulePath ):]
30+ // shortFilePath returns "parent_dir/filename.go" from any absolute or
31+ // module-relative path. This is independent of the build environment (no
32+ // -trimpath needed) and keeps Prometheus label cardinality manageable.
33+ func shortFilePath (file string ) string {
34+ dir , base := path .Split (file )
35+ parent := path .Base (dir )
36+ if parent == "." || parent == "/" {
37+ return base
3938 }
40- return file
39+ return parent + "/" + base
4140}
4241
4342// --- slog handler wrapper ---
@@ -75,7 +74,7 @@ func (h *MetricsSlogHandler) Handle(ctx context.Context, r slog.Record) error {
7574 frames := runtime .CallersFrames ([]uintptr {r .PC })
7675 f , _ := frames .Next ()
7776 if f .File != "" {
78- file = trimModulePrefix (f .File )
77+ file = shortFilePath (f .File )
7978 }
8079 pcFileCache .Store (r .PC , file )
8180 }
@@ -116,7 +115,7 @@ func WrapCoreWithLogMetrics(core zapcore.Core) zapcore.Core {
116115 }
117116 file := "unknown"
118117 if e .Caller .Defined {
119- file = trimModulePrefix (e .Caller .File )
118+ file = shortFilePath (e .Caller .File )
120119 }
121120 LogMessagesTotal .WithLabelValues (level , file ).Inc ()
122121 }
0 commit comments