Skip to content

Commit 71e5335

Browse files
sindrerh2ybelMekk
andcommittedNov 5, 2024·
add subcommand label in metric
Co-authored-by: ybelmekk <youssef.bel.mekki@nav.no> Co-authored-by: Carl Hedgren<carl.hedgren@nav.no>
1 parent 1fff5b5 commit 71e5335

File tree

1 file changed

+16
-8
lines changed

1 file changed

+16
-8
lines changed
 

‎pkg/metrics/otel.go

+16-8
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ import (
55
"github.com/urfave/cli/v2"
66
"log"
77
"os"
8-
"strings"
98
"time"
109

1110
"go.opentelemetry.io/otel/attribute"
@@ -56,7 +55,15 @@ func recordCommandUsage(ctx context.Context, provider *metric.MeterProvider, fla
5655
naisCliPrefixName+"_command_usage",
5756
m.WithUnit("1"),
5857
m.WithDescription("Usage frequency of command flags"))
59-
commandHistogram.Record(ctx, 1, m.WithAttributes(attribute.String("command", strings.Join(flags, "_"))))
58+
if flags != nil {
59+
commandHistogram.Record(ctx, 1, m.WithAttributes(attribute.String("command", flags[0])))
60+
}
61+
for i, f := range flags {
62+
if i == 0 {
63+
continue
64+
}
65+
commandHistogram.Record(ctx, 1, m.WithAttributes(attribute.String("subcommand", f)))
66+
}
6067
}
6168

6269
// intersection
@@ -88,22 +95,23 @@ func intersection(list1, list2 []string) []string {
8895
}
8996

9097
func CollectCommandHistogram(commands []*cli.Command) {
98+
doNotTrack := os.Getenv("DO_NOT_TRACK")
99+
if doNotTrack == "1" {
100+
log.Default().Println("DO_NOT_TRACK is set, not collecting metrics")
101+
}
102+
91103
ctx := context.Background()
92104
var validSubcommands []string
93105
for _, command := range commands {
94106
gatherCommands(command, &validSubcommands)
95107
}
96108

97-
doNotTrack := os.Getenv("DO_NOT_TRACK")
98-
if doNotTrack == "1" {
99-
log.Default().Println("DO_NOT_TRACK is set, not collecting metrics")
100-
}
101-
102109
res, _ := newResource()
103110
provider := newMeterProvider(res)
104-
defer provider.Shutdown(ctx)
111+
105112
// Record usages of subcommands that are exactly in the list of args we have, nothing else
106113
recordCommandUsage(ctx, provider, intersection(os.Args, validSubcommands))
114+
provider.Shutdown(ctx)
107115
}
108116

109117
func gatherCommands(command *cli.Command, validSubcommands *[]string) {

0 commit comments

Comments
 (0)
Please sign in to comment.