Elastic APM Python Agent
The official Python module for Elastic APM. It provides full out-of-the-box support for many popular frameworks, including Django and Flask, and can be adapted for most WSGI-compatible web applications or used in any standalone Python application. It monitors applications in real-time, collecting performance metrics, tracing transactions, and capturing errors. Currently at version 6.25.0, it sees regular updates focusing on framework compatibility and performance.
Warnings
- breaking Python 3.6 support will be removed in version 7.0.0 of the agent. Projects using Python 3.6 must upgrade to Python 3.7+ before upgrading to agent version 7.0.0 or later.
- deprecated The log shipping `LoggingHandler` will be removed in version 7.0.0. Consider using built-in log shipping via `logging=LEVEL` in the `ElasticAPM` constructor or filebeat for less urgent logs.
- gotcha When integrating with Flask and uWSGI, ensure that threads are explicitly enabled in your uWSGI configuration, as the APM agent relies on background threads for metrics collection and other operations.
- gotcha Compatibility with APM Server versions is crucial. For APM Server 6.2 and higher, ensure you are using `elastic-apm` agent version 2.0 or higher.
- gotcha In `v6.25.0`, a change in Tornado 6.5.3's `HttpHeaders` `in` operator behavior was handled. If using Tornado and upgrading it, ensure you are on `elastic-apm` v6.25.0+ to avoid potential issues.
- gotcha When running in FIPS mode (Federal Information Processing Standard), server certificate verification becomes mandatory for secure communication with the APM Server.
Install
-
pip install elastic-apm -
pip install elastic-apm[flask] -
pip install elastic-apm[django]
Imports
- Client
from elasticapm import Client
- ElasticAPM
from elasticapm.contrib.flask import ElasticAPM
- capture_span
from elasticapm import capture_span
Quickstart
import os
from flask import Flask
from elasticapm.contrib.flask import ElasticAPM
app = Flask(__name__)
app.config['ELASTIC_APM'] = {
'SERVICE_NAME': os.environ.get('ELASTIC_APM_SERVICE_NAME', 'my-flask-app'),
'SERVER_URL': os.environ.get('ELASTIC_APM_SERVER_URL', 'http://localhost:8200'),
'ENVIRONMENT': os.environ.get('ELASTIC_APM_ENVIRONMENT', 'development'),
'CAPTURE_HEADERS': True,
'TRANSACTIONS_IGNORE_PATTERNS': ['^/healthcheck']
}
apm = ElasticAPM(app)
@app.route('/')
def hello_world():
apm.client.capture_message('Hello World request received!')
try:
1 / 0
except ZeroDivisionError:
apm.client.capture_exception()
return 'Hello, World!'
@app.route('/healthcheck')
def healthcheck():
return 'OK'
if __name__ == '__main__':
# Set environment variables or ensure APM server is running at localhost:8200
# For example: ELASTIC_APM_SERVICE_NAME=my-service ELASTIC_APM_SERVER_URL=http://localhost:8200 python your_app.py
app.run(debug=True)