@@ -26,8 +26,7 @@ func BaseCommandAttributes(cmd *cobra.Command, streams Streams) []attribute.KeyV
2626// Note: this should be the last func to wrap/modify the PersistentRunE/RunE funcs before command execution.
2727//
2828// can also be used for spans!
29- func (cli * DockerCli ) InstrumentCobraCommands (cmd * cobra.Command , mp metric.MeterProvider ) {
30- meter := getDefaultMeter (mp )
29+ func (cli * DockerCli ) InstrumentCobraCommands (ctx context.Context , cmd * cobra.Command ) {
3130 // If PersistentPreRunE is nil, make it execute PersistentPreRun and return nil by default
3231 ogPersistentPreRunE := cmd .PersistentPreRunE
3332 if ogPersistentPreRunE == nil {
@@ -55,17 +54,27 @@ func (cli *DockerCli) InstrumentCobraCommands(cmd *cobra.Command, mp metric.Mete
5554 }
5655 cmd .RunE = func (cmd * cobra.Command , args []string ) error {
5756 // start the timer as the first step of every cobra command
58- baseAttrs := BaseCommandAttributes (cmd , cli )
59- stopCobraCmdTimer := startCobraCommandTimer (cmd , meter , baseAttrs )
57+ stopInstrumentation := cli .StartInstrumentation (ctx , cmd )
6058 cmdErr := ogRunE (cmd , args )
61- stopCobraCmdTimer (cmdErr )
59+ stopInstrumentation (cmdErr )
6260 return cmdErr
6361 }
6462
6563 return ogPersistentPreRunE (cmd , args )
6664 }
6765}
6866
67+ // StartInstrumentation instruments CLI commands with the individual metrics and spans configured.
68+ // It's the main command OTel utility, and new command-related metrics should be added to it.
69+ // It should be called immediately before command execution, and returns a stopInstrumentation function
70+ // that must be called with the error resulting from the command execution.
71+ func (cli * DockerCli ) StartInstrumentation (ctx context.Context , cmd * cobra.Command ) (stopInstrumentation func (error )) {
72+ mp := cli .MeterProvider (ctx )
73+ meter := getDefaultMeter (mp )
74+ baseAttrs := BaseCommandAttributes (cmd , cli )
75+ return startCobraCommandTimer (cmd , meter , baseAttrs )
76+ }
77+
6978func startCobraCommandTimer (cmd * cobra.Command , meter metric.Meter , attrs []attribute.KeyValue ) func (err error ) {
7079 ctx := cmd .Context ()
7180 durationCounter , _ := meter .Float64Counter (
0 commit comments