Python Apm Setup
Prerequisites
- To monitor APM data on dashboard, Middleware Host agent needs to be installed.
- You can refer this demo project to refer use cases of APM.
Step 1 : Install Python package
Run this in your terminal
pip install middleware-apm
Step 2 : Import Tracker
Add these line at the very start of your project
from apmpythonpackage import apmpythonclass
tracker=apmpythonclass()
tracker.mw_tracer({APM-PROJECT-NAME}, {APM-SERVICE-NAME})
Distributed Tracing
The middleware-bootstrap -a install command reads through the list of packages installed in your active site-packages folder, and installs the corresponding instrumentation libraries for these packages, if applicable.
middleware-bootstrap -a install
Run the below command for Distributed Tracing:
middleware-instrument --resource_attributes=project.name={APM-PROJECT-NAME} --metrics_exporter none --exporter_otlp_endpoint http://localhost:9319 --traces_exporter otlp --service_name {APM-SERVICE-NAME} python3 <your-file-name>.py
Note for APM inside Kubernetes
If you are using APM in a Kubernetes cluster make sure to follow these 2 steps:
Step 1 : Find your Middleware Service namespace
For older setup, your “mw-service” can be inside mw-agent-ns-{FIRST-5-LETTERS-OF-API-KEY}
namespace
For newer setup, we simplified the namespace name to mw-agent-ns
Step 2 : Set this ENV variable in your application deployment YAML
MW_AGENT_SERVICE=mw-service.NAMESPACE.svc.cluster.local
Note :
If you get a warning similar to the one given below :
WARNING: The scripts middleware-bootstrap and middleware-instrument are installed in '/home/.../.local/bin' which is not on PATH.
Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location
You can add the binary to your path In linux, you can add this with
export PATH=$PATH:/home/.../.local/bin
Add custom logs
tracker.error('python error log sample')
tracker.debug('ipython debug log sample')
tracker.warn('python warning log sample')
tracker.info('python info log sample')
Python Logging with Middleware
handler = tracker.mw_handler()
logging.getLogger().addHandler(handler)
logging.error("error log sample")
Error Handling :
If you want to record exception in traces then you can use tracker.record_error(e) method.
randomList = ['a', 0, 2]
for entry in randomList:
try:
r = 1/int(entry)
break
except Exception as e:
tracker.record_error(e)