Flask-Datadog
Flask-Datadog is a micro-framework extension for Flask applications, providing access to DogStatsD for custom metrics. Last updated in 2017, it offers a simple wrapper around the `datadog` library's StatsD and API clients. For comprehensive application performance monitoring (APM), tracing, and logging with Flask, Datadog's officially supported `ddtrace` library is the current recommended solution.
Common errors
-
ModuleNotFoundError: No module named 'flask.ext.datadog'
cause You are attempting to import `flask_datadog` using the deprecated `flask.ext` namespace, which was removed in Flask 1.0.fixChange your import statement from `from flask.ext.datadog import ...` to `from flask_datadog import ...`. -
ConnectionRefusedError: [Errno 111] Connection refused
cause The Datadog Agent's DogStatsD server is not running or is not accessible at the configured `STATSD_HOST` and `STATSD_PORT`.fixEnsure the Datadog Agent is installed and running, and that its DogStatsD port (default 8125) is open and reachable from your Flask application. Verify `app.config['STATSD_HOST']` and `app.config['STATSD_PORT']` are correctly set.
Warnings
- deprecated The `flask.ext` import mechanism, commonly shown in older `flask-datadog` examples, is deprecated since Flask 0.11 and removed in Flask 1.0. Attempting to use it with modern Flask will result in an `ImportError` or `ModuleNotFoundError`.
- gotcha `flask-datadog` is an older library (last updated 2017) primarily for StatsD metrics. For comprehensive Datadog integration, including APM, distributed tracing, and advanced logging, Datadog officially recommends using the `ddtrace` library with its automated instrumentation for Flask applications.
Install
-
pip install Flask-Datadog
Imports
- API
from flask_datadog import API
- StatsD
from flask.ext.datadog import StatsD
from flask_datadog import StatsD
Quickstart
from flask import Flask
from flask_datadog import API, StatsD
import os
app = Flask(__name__)
# Configure Datadog API and StatsD settings
app.config['STATSD_HOST'] = os.environ.get('DATADOG_STATSD_HOST', 'localhost')
app.config['STATSD_PORT'] = int(os.environ.get('DATADOG_STATSD_PORT', '8125'))
app.config['DATADOG_API_KEY'] = os.environ.get('DATADOG_API_KEY', '')
app.config['DATADOG_APP_KEY'] = os.environ.get('DATADOG_APP_KEY', '')
statsd = StatsD(app)
dogapi = API(app)
@app.route('/')
def hello():
statsd.increment('my_flask_app.requests')
return 'Hello, Datadog!'
@app.route('/error')
def error_route():
statsd.increment('my_flask_app.errors')
# Example of API usage (requires valid API/App keys)
# if dogapi.api_key and dogapi.app_key:
# dogapi.Event.create('An error occurred in Flask app',
# tags=['env:dev', 'service:my-app'])
raise Exception('This is a test error!')
if __name__ == '__main__':
# Ensure the Datadog Agent is running and accessible at STATSD_HOST:STATSD_PORT
# For API calls, ensure DATADOG_API_KEY and DATADOG_APP_KEY are set.
app.run(debug=True)