|
1 | 1 | from time import sleep |
2 | 2 | import click |
3 | | -from cli_telemetry.telemetry import start_session, end_session, profile, add_tag, profile_block |
4 | 3 |
|
| 4 | +# import this first so it can patch click before any commands are defined |
| 5 | +import cli_telemetry.telemetry as telemetry |
| 6 | +from cli_telemetry.telemetry import profile, add_tag, profile_block |
5 | 7 |
|
6 | | -@click.group() |
7 | | -@click.pass_context |
8 | | -def cli(ctx): |
9 | | - """ |
10 | | - Example CLI with telemetry instrumentation. |
11 | | - """ |
12 | | - # Start the root span for this invocation |
13 | | - cmd = ctx.invoked_subcommand or "cli" |
14 | | - start_session(command_name=cmd, service_name="example-cli") |
15 | | - # Ensure we end the span when the CLI exits |
16 | | - ctx.call_on_close(end_session) |
| 8 | +telemetry.init_telemetry("example-cli") |
17 | 9 |
|
| 10 | +@click.group() |
| 11 | +def cli(): |
| 12 | + """Example CLI with telemetry instrumentation.""" |
| 13 | + # no manual start_session() or call_on_close() needed any more |
| 14 | + pass |
18 | 15 |
|
19 | 16 | @cli.command() |
20 | 17 | @click.argument("message") |
21 | | -@profile |
22 | 18 | def echo(message): |
23 | 19 | """Prints the message as-is.""" |
24 | 20 | # Tag the argument so it shows up on this span |
25 | 21 | add_tag("args.message", message) |
26 | 22 | click.echo(message) |
27 | 23 |
|
28 | | - |
29 | 24 | @cli.command() |
30 | 25 | @click.argument("message") |
31 | 26 | @click.option("--times", "-n", default=1, show_default=True, help="How many times to shout") |
32 | | -@profile |
33 | 27 | def shout(message, times): |
34 | 28 | """Prints the message uppercased with exclamation.""" |
35 | 29 | add_tag("args.message", message) |
36 | 30 | add_tag("args.times", times) |
37 | 31 | for _ in range(times): |
38 | 32 | click.echo(f"{message.upper()}!") |
39 | 33 |
|
40 | | - |
41 | 34 | @cli.command() |
42 | | -@profile |
43 | 35 | def work(): |
44 | 36 | """Simulate some nested work using a profile_block.""" |
45 | 37 | add_tag("phase", "start_work") |
46 | 38 | with profile_block("step_1", tags={"step": 1}): |
47 | 39 | click.echo("step1") |
48 | 40 | sleep(0.1) |
49 | | - pass |
50 | 41 | with profile_block("step_2", tags={"step": 2}): |
51 | 42 | click.echo("step2") |
52 | 43 | sleep(0.2) |
53 | | - pass |
54 | 44 | click.echo("Work done!") |
55 | 45 |
|
56 | | - |
57 | 46 | if __name__ == "__main__": |
58 | 47 | cli() |
0 commit comments