ddtrace-asgi

Unofficial ddtrace integration for ASGI apps and frameworks


Keywords
asgi, datadog, python, tracing
License
BSD-3-Clause
Install
pip install ddtrace-asgi==0.3.0

Documentation

ddtrace-asgi

Build Status Coverage Package version

Unofficial ddtrace integration for ASGI apps and frameworks.

Should work seamlessly for any ASGI web framework, e.g. Starlette, FastAPI, Quart, etc.

Note: This project is in alpha stage.

Requirements

  • Python 3.6+.
  • ddtrace must be installed to use the ddtrace-run command.
  • The Datadog Agent must be installed and running for traces to be effectively sent to Datadog APM.

Installation

pip install ddtrace-asgi

Quickstart

To automatically send traces to Datadog APM on each HTTP request, wrap your ASGI application around TraceMiddleware:

# app.py
from ddtrace_asgi.middleware import TraceMiddleware

async def app(scope, receive, send):
    assert scope["type"] == "http"
    headers = [[b"content-type", b"text/plain"]]
    await send({"type": "http.response.start", "status": 200, "headers": headers})
    await send({"type": "http.response.body", "body": b"Hello, world!"})

app = TraceMiddleware(
    app, service="asgi-hello-world", tags={"env": "local"},
)

Then use ddtrace-run when serving your application. For example, if serving with Uvicorn:

ddtrace-run uvicorn app:app

For more information on using ddtrace, please see the official dd-trace-py repository.

Examples

Starlette

from ddtrace_asgi.middleware import TraceMiddleware
from starlette.applications import Starlette

app = Starlette()
app.add_middleware(TraceMiddleware, service="my-starlette-app")

FastAPI

from ddtrace_asgi.middleware import TraceMiddleware
from fastapi import FastAPI

app = FastAPI()
app.add_middleware(TraceMiddleware, service="my-fastapi-app")

API Reference

TracingMiddleware

class TracingMiddleware:
    def __init__(self, app, tracer=None, service="asgi", tags=None, distributed_tracing=True):
        ...

An ASGI middleware that sends traces of HTTP requests to Datadog APM.

Parameters

  • app - An ASGI application.
  • tracer - (optional) A Tracer object. Defaults to the global ddtrace.tracer object.
  • service - (optional) Name of the service as it will appear on Datadog.
  • tags - (optional) Default tags attached to all request spans. Either a dictionary, or a string of comma-separated tags (e.g. "env:staging, app:shop"). See also Tagging.
  • distributed_tracing - (optional) Whether to enable distributed tracing.