Introducing a new way to review your PRs.

Read the announcement

azure / azure-cli

Azure Command-Line Interface

View on GitHub

13 documents · Updated Nov 16, 2026

docs / telemetry-package

Azure CLI Telemetry Package

Overview

Routing/coverage note: this doc owns src/azure-cli-telemetry/**, the Azure CLI core integration point src/…/telemetry.py, and developer-facing telemetry docs under doc/telemetry/**.

Azure CLI telemetry is split between event construction in core and upload/storage mechanics in the azure-cli-telemetry package. The core singleton _session in src/…/telemetry.py accumulates one command's state: command name, output type, parameters, result, timing, extension metadata, authentication details, secret-detection fields, custom extension/interactive events, and exceptions. Public setters such as start, set_command_details, set_success, set_failure, set_exception, set_debug_info, set_secrets_detected, add_extension_event, and add_dedicated_instrumentation_key mutate that singleton while command execution proceeds. flush() and conclude() check is_telemetry_enabled() before writing; telemetry is disabled when azure.cli.core.cloud.cloud_forbid_telemetry forbids it or when application config core.collect_telemetry is false.

TelemetrySession.generate_payload() in src/…/telemetry.py builds a JSON object keyed by Application Insights instrumentation key. The default key comes from DEFAULT_INSTRUMENTATION_KEY in src/…/__init__.py; dedicated keys can be added for extension-specific events. The default command event is named azurecli/command and merges base properties, Azure CLI properties, and user-task result fields. Fault events are named azurecli/fault; they keep legacy exception records in self.exceptions, add fault-specific Reserved.DataModel.* fields, and correlate back to the command through Reserved.DataModel.Correlation.1. Custom extension and interactive events are added directly to _session.events by add_extension_event and add_interactive_event, with Reserved.DataModel.CorrelationId injected by _add_event.

The command properties in src/…/telemetry.py are intentionally sanitized and normalized before upload. _remove_symbols removes shell-sensitive characters from the serialized payload; _remove_cmd_chars strips quotes and newlines from summaries and command-derived strings. _get_hash_mac_address, _get_hash_machine_id, _get_user_azure_id, and _get_session_id avoid sending raw identifiers. _process_config_set_debug_info only records values for entries allowed by ALLOWED_CONFIG_SECTIONS_OR_KEYS; other config values are replaced with ***. CLI context is read from the application object, profile, active cloud, configuration, environment variables beginning with AZURE_CLI, and user-agent helpers.

The azure-cli-telemetry package exposes save(config_dir, payload) and the upload-process entry point in src/…/__init__.py. save() first splits the generated payload by instrumentation key. Events for the default CLI key are persisted to disk for asynchronous upload, while events for non-default keys are sent immediately through CliTelemetryClient to avoid routing extension-specific telemetry through the CLI cache. If splitting fails, save() falls back to caching the original payload.

Default-key events are cached by save_payload() in src/…/util.py. It creates a per-save directory under <config_dir>/telemetry/<YYYYMMDDHHMMSSmmm>/, writes a rotating cache file there, and formats each line as <timestamp>,<payload>. Successful saves return that directory path. save() then starts a detached Python process running azure/…/__init__.py with config_dir and the specific cache directory as arguments. The child process configures file logging through config_logging_for_upload() in src/…/telemetry_logging.py, writing <config_dir>/…/telemetry.log with a 10 MB rotating handler.

The upload child in src/…/__init__.py reads only the cache directory it was passed. RecordsCollection.snapshot_and_read() in src/…/records_collection.py scans regular files in that directory, reads every line, strips the timestamp by splitting on the first comma, appends the JSON payload to the in-memory collection, and removes the entire cache directory after reading. The collection is then streamed into CliTelemetryClient.add(..., flush=True) and finally flush(force=True).

CliTelemetryClient in src/…/telemetry_client.py parses each cached JSON string into instrumentation-key groups, creates an Application Insights TelemetryClient per key, and tracks each record by name. String-valued record properties are sent as Application Insights properties; non-strings become measurements. The default batch threshold is 100 events, but callers can force a flush. _NoRetrySender overrides the Application Insights synchronous sender to post a JSON envelope with a 10-second timeout and log upload failures without retrying.

TelemetryNote in src/…/telemetry_note.py still provides a portalocker-based lock file at <config_dir>/telemetry.txt, timestamp parsing, timestamp updates, and mtime touching. The current upload entry point no longer imports it, but src/…/test_telemetry_note.py preserves its locking and timestamp behavior.

Tests under src/azure-cli-telemetry/azure/cli/telemetry/tests/ exercise the package-level upload pieces rather than the full CLI command lifecycle. test_telemetry_client.py validates batching, forced flush, Application Insights envelope shape, the 10-second sender timeout, and no-retry behavior for HTTP, OS, and unexpected errors. test_records_collection.py copies resource cache files and verifies that RecordsCollection removes the cache directory and loads 1,758 records. test_telemetry_logging.py checks telemetry logger names and upload-process log-file creation. test_telemetry_note.py checks TelemetryNote file creation, locking, timestamp parsing, and updates.

Developer docs under doc/telemetry/ describe how emitted records are queried downstream. doc/…/README.md distinguishes ARM telemetry from CLI client telemetry and documents important RawEventsAzCli fields such as EventName, CorrelationId, ProductVersion, RawCommand, Params, ActionResult, and error fields. doc/…/faq.md points extension authors to add_extension_event and explains core.collect_telemetry. doc/…/kusto_examples.md provides Kusto queries for schema filtering, command usage, extension versions, success rate, and failure details.

Coupling

  • If event property names or event names change in src/…/telemetry.py, update doc/…/README.md, doc/…/faq.md, and doc/…/kusto_examples.md; those docs teach consumers to query exact strings such as azurecli/command, azurecli/fault, azurecli/extension, context.default.azurecli.extensionname, context.default.azurecli.error_type, and Reserved.DataModel.CorrelationId.
  • If the payload structure returned by TelemetrySession.generate_payload() in src/…/telemetry.py changes, update both save() in src/…/__init__.py and CliTelemetryClient.add() in src/…/telemetry_client.py; both expect a JSON object mapping instrumentation key to a list of records with name and properties fields.
  • If DEFAULT_INSTRUMENTATION_KEY changes in src/…/__init__.py, verify TelemetrySession.__init__() in src/…/telemetry.py and the split logic in save() together. Default-key events are cached for background upload, while non-default keys are uploaded immediately.
  • If the cache line format in save_payload() in src/…/util.py changes, update RecordsCollection._add_record() in src/…/records_collection.py; it currently assumes every line contains one timestamp followed by a comma and the JSON payload.
  • If the upload process arguments change in _start() or main() in src/…/__init__.py, update them together. _start() launches sys.executable, this package's __init__.py, config_dir, and cache_dir; main() exits with status 1 when either argument is missing.
  • If new telemetry values may contain secrets, route them through the sanitization patterns in src/…/telemetry.py. set_debug_info() masks config values outside ALLOWED_CONFIG_SECTIONS_OR_KEYS, summaries are passed through _remove_cmd_chars, and the whole payload is passed through _remove_symbols before saving.
  • If package dependencies change in src/…/pyproject.toml, verify the code paths that import them lazily. applicationinsights is imported by src/…/telemetry_client.py; portalocker is imported by the upload error handling in src/…/__init__.py and by TelemetryNote in src/…/telemetry_note.py.

Risks

  • Cache-directory concurrency is fragile across src/…/util.py, src/…/__init__.py, and src/…/records_collection.py. Commit 556d19898 explicitly fixed telemetry loss by switching from one shared cache directory plus TelemetryNote timestamps to per-save cache directories passed to the upload process; reintroducing shared-directory scanning or timestamp filtering can drop concurrent command telemetry.
  • RecordsCollection.snapshot_and_read() in src/…/records_collection.py deletes the cache directory after reading. If save_payload() in src/…/util.py ever writes multiple command payloads to the same directory again, one upload worker can remove records another worker still needs.
  • _NoRetrySender.send() in src/…/telemetry_client.py intentionally logs HTTPError, OSError, and unexpected exceptions without retrying. If Application Insights is temporarily unavailable, the cached records for that upload attempt are already removed by RecordsCollection.snapshot_and_read() and will not be retried later.
  • The package still contains TelemetryNote and MANDATORY_WAIT_PERIOD in src/…/telemetry_note.py and src/…/const.py, but the current upload path in src/…/__init__.py no longer uses them. Reusing those pieces for upload throttling would need a fresh concurrency review against the per-cache-directory design from commit 556d19898.