Python

TracesMetricsApp LogsCustom LogsProfiling

This guide walks you through setting up Application Performance Monitoring (APM) on a Python application. These instructions can also be found on the Installation page in your Middleware Account. View example code here.

Prerequisites

1 Python Version

Python 3 version 3.8 or above. Check your Python version with the following command:

2 Pip Version

pip version 23.1.2 or above. Check your pip version with the following command:

Installation

Step 1: Install Python APM Package

Run the following command in your terminal:

Check if the middleware-apm has been installed with the following command:

Step 2: Initialize Middleware APM

Run the following command to generate the default middleware.ini config and bootstrap and install the required instrumentation packages (which internally uses opentelemetry-bootstrap --action=install):

Step 3: Import Middleware Tracker

Add the following lines to the entry point of your application, and as the first import:

Step 4: Instrumentation Configuration

After initializing the APM using middleware-apm init, a default middleware.ini file is created at the root of your app directory.

This file contains the configuration for your application's instrumentation, such as traces, metrics, logs, and profiling.

You can modify the configuration directly inside the file or by using environment variables.

service_name and access_token are required for the tracker to send data to Middleware.

If the file's location is any other but the root of your app dir you'll need to set the MIDDLEWARE_CONFIG_FILE environment variable to the new location.

Sample Configuration File (middleware.ini)

The Common Attributes are ones we suggest always using, while the ones commented out are dependent on your use case.

Available Configs and Env Variables

This table shows the available configuration settings from the above config file along with the corresponding environment variables that can be used instead.

Config AttributeEnvironment VariableDescription
service_nameMW_SERVICE_NAME or OTEL_SERVICE_NAMEThe name of your application as service_name, as it will appear in the UI to filter your data. Defaults to service-pid if not declared.
access_tokenMW_API_KEYToken required to bind the Python Agent's data for profiling and serverless usage.
collect_tracesMW_APM_COLLECT_TRACESToggle to enable/disable traces for your application. Optional, default is True.
collect_metricsMW_APM_COLLECT_METRICSToggle to enable/disable the collection of metrics for your application. Optional, default is False.
collect_logsMW_APM_COLLECT_LOGSToggle to enable/disable the collection of logs for your application. Optional, default is True.
collect_profilingMW_APM_COLLECT_PROFILINGToggle to enable/disable the collection of profiling data. Optional, default is False.
log_levelMW_LOG_LEVEL or OTEL_LOG_LEVELSets the log level (DEBUG, INFO, WARNING, ERROR, CRITICAL, FATAL). Optional, default is INFO.
mw_agent_serviceMW_AGENT_SERVICESet with agent for K8s or Docker based application. Should not be used for serverless applications.
targetMW_TARGET or OTEL_EXPORTER_OTLP_ENDPOINTSet target for instrumentation without an agent. Optional for serverless applications.
custom_resource_attributesMW_CUSTOM_RESOURCE_ATTRIBUTESCustom resource attributes for traces, metrics, and logs (key1=value1, key2=value2). Optional.
otel_propagatorsMW_PROPAGATORS or OTEL_PROPAGATORSEnable and change Context Propagators (default: B3). Optional.
disable_infoMW_DISABLE_INFODisable information for APM. Optional, default is false.
console_exporterMW_CONSOLE_EXPORTEREnable exporting traces, metrics, and logs to the console. Optional, default is false.
debug_log_fileMW_DEBUG_LOG_FILESave console-exported logs, metrics, and traces to separate files. Works only if console_exporter is enabled.
project_nameMW_PROJECT_NAMEAssign a project name to the service. Optional.

All OpenTelemetry environment variables are supported and take the highest priority.

Step 5: Start Your Project

Run the following command to start your project with instrumentation:

Host Based Configuration

If you are deploying the host using Kubernetes or Docker you will need to set the mw_agent_service to the location of the mw-agent.

This variable can be ignored when the agent is running on the same host as the application.

Docker
Kubernetes

Add the mw_agent_service or export environment variable to your application:

The DOCKER_BRIDGE_GATEWAY_ADDRESS is the IP address of the gateway between the Docker host and bridge network. This is 172.17.0.1 by default. Learn more about Docker bridge networking here

Add the following command to your Dockerfile after the pip install command:

Identify the namespace where the Infra Agent is running:

Then add the following environment variable to your application deployment YAML file:

Serverless Configuration

If you are running your Python application in a serverless setup without the mw-agent, the MW_API_KEY and MW_TARGET variables are required when running the application:

Framework Specific Configurations

Specific frameworks require different configurations when being run, which can be found below:

Django
Gunicorn
Uvicorn

Sending Custom Data

Custom Metrics

Create and use a meter to send custom metrics:

Custom Traces

Create and use a tracer to send custom spans:

Custom Logs

Utilize Middleware's logging method to send logs with a given priority. It is recommended to integrate these calls function inside your existing logger:

Custom Attributes

All custom attributes collected will be available as filtering and grouping functions inside of the Middleware platform.

Using similar methods from the above Traces and Logs sections you can attach custom attributes to any trace, span or log:

Adding Stack Traces

Use tracker.record_error() method to record a stack trace when an error occurs:

Continuous Profiling

By default the Python APM captures Continuous Profiling data which provides real-time performance insights from your application to enable rapid identification of resource allocation, bottlenecks, and more. Navigate to the Continuous Profiling section to learn more about using Continuous Profiling with Middleware.

Example application

Below is a sample python flask server application.

Start the server

Troubleshooting and Debugging

To help troubleshoot and debug issues with your application's telemetry, you can enable specific settings in the middleware.ini file or use environment variables. These settings allow you to export telemetry data to the console, save them to log files, or disable basic information logs.

Toggling Basic Information Logs

Toggle info logs on or off to focus on debugging specific issues:

Exporting Telemetry Data to the Console

When debugging in a dev environment it may be useful to view the telemetry data directly in the console. Setting the console_exporter to true will print telemetry data like traces, metrics, and logs in your terminal or console.

Saving Telemetry Data to Log Files

You may save telemetry data to log files by enabling the debug_log_file setting. The logs will be written to respective files such as mw-traces.log, mw-metrics.log, and mw-logs.log.

Python package installation failure

The Python package installs require gcc and gcc-c++, which you may need to install if you’re running a slim version of Linux, such as CentOS.

CentOS
Debian/Ubuntu
Alpine

Need assistance or want to learn more about Middleware? Contact our support team in Slack.