Package: azure-monitor-opentelemetry
Azure Monitor Opentelemetry Distro client library for PythonThe Azure Monitor Distro ofOpentelemetry Pythonprovides multiple installable components available for an Opentelemetry Azure Monitor monitoring solution. It allows you to instrument your Python applications to capture and report telemetry to Azure Monitor via the Azure monitor exporters.This distro automatically installs the following libraries:Azure Monitor OpenTelemetry exportersA subset of OpenTelemetryinstrumentationsthat are officially supported as listed below.Officially supported instrumentationsOpenTelemetry instrumentations allow automatic collection of requests sent from underlying instrumented libraries. The following is a list of OpenTelemetry instrumentations that come bundled in with the Azure monitor distro. These instrumentations are enabled by default. See theUsagesection below for how to opt-out of these instrumentations.InstrumentationSupported library NameSupported versionsAzure Core Tracing OpenTelemetryazure_sdkOpenTelemetry Django InstrumentationdjangolinkOpenTelemetry FastApi InstrumentationfastapilinkOpenTelemetry Flask InstrumentationflasklinkOpenTelemetry Psycopg2 Instrumentationpsycopg2linkOpenTelemetry Requests InstrumentationrequestslinkOpenTelemetry UrlLib InstrumentationurllibAllOpenTelemetry UrlLib3 Instrumentationurllib3linkIf you would like to add support for another OpenTelemetry instrumentation, please submit a featurerequest. In the meantime, you can use the OpenTelemetry instrumentation manually via it's own APIs (i.e.instrument()) in your code. Seethisfor an example.Key conceptsThis package bundles a series of OpenTelemetry and Azure Monitor components to enable the collection and sending of telemetry to Azure Monitor. For MANUAL instrumentation, use theconfigure_azure_monitorfunction. AUTOMATIC instrumentation is not yet supported.TheAzure Monitor OpenTelemetry exportersare the main components in accomplishing this. You will be able to use the exporters and their APIs directly through this package. Please go the exporter documentation to understand how OpenTelemetry and Azure Monitor components work in enabling telemetry collection and exporting.Currently, all instrumentations available in OpenTelemetry are in a beta state, meaning they are not stable and may have breaking changes in the future. Efforts are being made in pushing these to a more stable state.Getting startedPrerequisitesTo use this package, you must have:Azure subscription -Create a free accountAzure Monitor -How to use application insightsOpentelemetry SDK -Opentelemetry SDK for PythonPython 3.7 or later -Install PythonInstall the packageInstall the Azure Monitor Opentelemetry Distro withpip:pipinstallazure-monitor-opentelemetryUsageYou can useconfigure_azure_monitorto set up instrumentation for your app to Azure Monitor.configure_azure_monitorsupports the following optional arguments. All pass-in parameters take priority over any related environment variables.ParameterDescriptionEnvironment Variableconnection_stringTheconnection stringfor your Application Insights resource. The connection string will be automatically populated from theAPPLICATIONINSIGHTS_CONNECTION_STRINGenvironment variable if not explicitly passed in.APPLICATIONINSIGHTS_CONNECTION_STRINGlogger_nameThe name of thePython loggerunder which telemetry is collected.N/Ainstrumentation_optionsA nested dictionary that determines which instrumentations to enable or disable. Instrumentations are referred to by theirLibrary Names. For example,{"azure_sdk": {"enabled": False}, "flask": {"enabled": False}, "django": {"enabled": True}}will disable Azure Core Tracing and the Flask instrumentation but leave Django and the other default instrumentations enabled. TheOTEL_PYTHON_DISABLED_INSTRUMENTATIONSenvironment variable explained below can also be used to disable instrumentations.N/AYou can configure further withOpenTelemetry environment variablessuch as:Environment VariableDescriptionOTEL_SERVICE_NAME,OTEL_RESOURCE_ATTRIBUTESSpecifies the OpenTelemetryResourceassociated with your application.OTEL_LOGS_EXPORTERIf set toNone, disables collection and export of logging telemetry.OTEL_METRICS_EXPORTERIf set toNone, disables collection and export of metric telemetry.OTEL_TRACES_EXPORTERIf set toNone, disables collection and export of distributed tracing telemetry.OTEL_BLRP_SCHEDULE_DELAYSpecifies the logging export interval in milliseconds. Defaults to 5000.OTEL_BSP_SCHEDULE_DELAYSpecifies the distributed tracing export interval in milliseconds. Defaults to 5000.OTEL_TRACES_SAMPLER_ARGSpecifies the ratio of distributed tracing telemetry to besampled. Accepted values are in the range [0,1]. Defaults to 1.0, meaning no telemetry is sampled out.OTEL_PYTHON_DISABLED_INSTRUMENTATIONSSpecifies which of the supported instrumentations to disable. Disabled instrumentations will not be instrumented as part ofconfigure_azure_monitor. However, they can still be manually instrumented withinstrument()directly. Accepts a comma-separated list of lowercaseLibrary Names. For example, set to"psycopg2,fastapi"to disable the Psycopg2 and FastAPI instrumentations. Defaults to an empty list, enabling all supported instrumentations.OTEL_EXPERIMENTAL_RESOURCE_DETECTORSAn experimental OpenTelemetry environment variable used to specify Resource Detectors to be used to generate Resource Attributes. This is an experimental feature and the name of this variable and its behavior can change in a non-backwards compatible way. Defaults to "azure_app_service,azure_vm" to enable theAzure Resource Detectorsfor Azure App Service and Azure VM. To add or remove specific resource detectors, set the environment variable accordingly. See theOpenTelemetry Python Resource Detector Documentationfor more.Azure monitor OpenTelemetry Exporter configurationsYou can pass Azure monitor OpenTelemetry exporter configuration parameters directly intoconfigure_azure_monitor. See additionalconfiguration related to exporting here....configure_azure_monitor(connection_string="<your-connection-string>",disable_offline_storage=True,)...ExamplesSamples are availablehereto demonstrate how to utilize the above configuration options.Monitoring in Azure FunctionsTrace correlationTracked incoming requests coming into your Python application hosted in Azure Functions will not be automatically correlated with telemetry being tracked within it. You can manually achieve trace correlation by extract theTraceContextdirectly as shown below:importazure.functionsasfuncfromazure.monitor.opentelemetryimportconfigure_azure_monitorfromopentelemetryimporttracefromopentelemetry.propagateimportextract# Configure Azure monitor collection telemetry pipelineconfigure_azure_monitor()defmain(req:func.HttpRequest,context)->func.HttpResponse:...# Store current TraceContext in dictionary formatcarrier={"traceparent":context.trace_context.Traceparent,"tracestate":context.trace_context.Tracestate,}tracer=trace.get_tracer(__name__)# Start a span using the current contextwithtracer.start_as_current_span("http_trigger_span",context=extract(carrier),):...Logging issuesThe Azure Functions worker itself sends logging telemetry itself without the use of the azure monitor sdk (the call toconfigure_azure_monitor()). This will cause you to possibly experience duplicate telemetry entries when sending logging telemetry. Our recommendation to customers is to use solely the SDK as it will allow much more rich telemetry and features than using the built in one provided by the Azure Functions worker. You can turn off the Azure Functions telemetry logger by clearing the list of handlers of your logger....root_logger=logging.getLogger()forhandlerinroot_logger.handlers[:]:root_logger.removeHandler(handler)...Be sure to call the above BEFORE any loggers or the call toconfigure_azure_monitor()is setup.You may also disable logging throughAzure Functions configuration.v2.x+...
{
  "logging": {
    ...
    "logLevel": {
      "default": "None",
      ...
    }
  }
}
...v1.x...
{
  "logger": {
    "categoryFilter": {
      "defaultLevel": "None",
      ...
    }
  }
}
...TroubleshootingThe exporter raises exceptions defined inAzure Core.Next stepsCheck out thedocumentationfor more.ContributingThis project welcomes contributions and suggestions.  Most contributions require you to agree to a
Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us
the rights to use your contribution. For details, visithttps://cla.microsoft.com.When you submit a pull request, a CLA-bot will automatically determine whether you need to provide
a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions
provided by the bot. You will only need to do this once across all repos using our CLA.This project has adopted theMicrosoft Open Source Code of Conduct.
For more information see theCode of Conduct FAQor
contactopencode@microsoft.comwith any additional questions or comments.Additional documentationAzure PortalOfficial Azure monitor docsOpenTelemetry Python Official Docs