Monitoring Python Applications with Elastic APM

Monitoring Flask / Flask-RESTPlus Applications

Installation

pip install elastic-apm[flask]

Implementation

from flask import Flask
from elasticapm.contrib.flask import ElasticAPM
import elasticapm

server_url = 'http://localhost:8200'
service_name = 'DemoFlask'
environment = 'dev'

app = Flask(__name__)
apm = ElasticAPM(app, server_url=server_url, service_name=service_name, environment=environment)


@app.before_request
def apm_log():
    elasticapm.label(platform = 'DemoPlatform',
                     application = 'DemoApplication')


@app.route('/hello-world/')
def helloWorld():
	return "Hello World"


app.run()

Monitoring FastAPI Applications

Installation

pip install elastic-apm

Implementation

import uvicorn
from fastapi import FastAPI

from elasticapm.contrib.starlette import make_apm_client, ElasticAPM


apm_config = {
	'SERVICE_NAME': 'DemoFastAPI',
	'SERVER_URL': 'http://localhost:8200',
	'ENVIRONMENT': 'dev',
	'GLOBAL_LABELS': 'platform=DemoPlatform, application=DemoApplication'
}

apm = make_apm_client(apm_config)

app = FastAPI()
app.add_middleware(ElasticAPM, client=apm)


@app.get('/hello-world/')
def hello_world():
	return "Hello World"


uvicorn.run(app)

Monitoring Python Applications

Installation

pip install elastic-apm

Implementation

import time
from apscheduler.schedulers.background import BackgroundScheduler

from elasticapm import Client
import elasticapm

client = Client(
    {'SERVICE_NAME': 'DemoPython',
     'SERVER_URL': 'http://localhost:8200',
     'ENVIRONMENT': 'dev'}
)

elasticapm.instrumentation.control.instrument()

def hello_world():
	client.begin_transaction('schedule')
	elasticapm.label(platform='DemoPlatform', application='DemoApplication')

	print("Hello World")

	client.end_transaction('demo-transaction', 'success')


if __name__ == "__main__":
	scheduler = BackgroundScheduler()
	scheduler.add_job(hello_world, 'interval', seconds=5)
	scheduler.start()
	print('Started scheduler..')
	print('Press Ctrl+C to exit')
	try:
		# Necessary to simulate application activity (which keeps the main thread alive).
		while True:
			time.sleep(2)
	except (KeyboardInterrupt, SystemExit):
		print('Shutting down scheduler')
		scheduler.shutdown()