Azure Application Insights Legacy Python SDK
This is the *legacy* Python SDK for sending telemetry to Azure Application Insights. It allows applications to send custom events, metrics, and traces directly to Application Insights. For new applications, it is strongly recommended to use the OpenTelemetry-based `azure-monitor-opentelemetry-distro` package. The `applicationinsights` package is currently at version 0.11.10 and receives minimal updates, primarily maintenance.
Warnings
- breaking This `applicationinsights` package is the *legacy* Python SDK for Azure Application Insights. For all new development and recommended usage, developers should use the `azure-monitor-opentelemetry-distro` package, which is based on OpenTelemetry and offers broader instrumentation and future compatibility.
- gotcha The legacy `applicationinsights` SDK uses an 'Instrumentation Key' for authentication. The modern OpenTelemetry-based SDK (`azure-monitor-opentelemetry-distro`) uses a 'Connection String'. These are distinct values and not interchangeable.
- gotcha Telemetry sent via `TelemetryClient` is buffered in memory. If your application exits abruptly or runs for a short period, you must explicitly call `client.flush()` to ensure all buffered telemetry is sent to Application Insights before termination.
- deprecated Support for Python 3.6 was dropped in the related OpenTelemetry-based SDK (v1.0.0b6). While this specific legacy package (0.11.10) might still work with Python 3.6, its maintenance status means future compatibility with older Python versions is not guaranteed, and it's unlikely to receive updates for new Python releases.
Install
-
pip install applicationinsights
Imports
- TelemetryClient
from applicationinsights import TelemetryClient
- logging
import logging from applicationinsights.logging import enable
Quickstart
import os
from applicationinsights import TelemetryClient
# For legacy SDK, use Instrumentation Key
# Find your Instrumentation Key in your Application Insights resource in Azure Portal.
INSTRUMENTATION_KEY = os.environ.get('APPINSIGHTS_INSTRUMENTATIONKEY', 'YOUR_LEGACY_INSTRUMENTATION_KEY')
if not INSTRUMENTATION_KEY or INSTRUMENTATION_KEY == 'YOUR_LEGACY_INSTRUMENTATION_KEY':
print("Warning: APPINSIGHTS_INSTRUMENTATIONKEY not set. Telemetry will not be sent.")
exit()
client = TelemetryClient(INSTRUMENTATION_KEY)
# Track an event
client.track_event('MyLegacyPythonEvent', {'custom_property': 'value1'})
# Track a metric
client.track_metric('MyLegacyMetric', 123.45)
# Track a trace message
client.track_trace('This is a legacy trace message', properties={'level': 'INFO'})
# Ensure telemetry is sent before application exits
client.flush()
print("Legacy telemetry sent.")