### Enable Ray Tracing with Startup Hook Source: https://ddtrace.readthedocs.io/en/stable/integrations.html Enable tracing for Ray by starting the Ray head node with the `--tracing-startup-hook` option pointing to the Datadog tracing setup function. ```bash ray start --head --tracing-startup-hook=ddtrace.contrib.ray:setup_tracing ``` -------------------------------- ### CherryPy Integration Example Source: https://ddtrace.readthedocs.io/en/stable/integrations.html A complete example of integrating CherryPy with Datadog tracing, including middleware setup, tool decoration, and a basic application. ```python import cherrypy from ddtrace.contrib.cherrypy import TraceMiddleware TraceMiddleware(cherrypy, service="my-cherrypy-app") @cherrypy.tools.tracer() class HelloWorld(object): def index(self): return "Hello World" index.exposed = True cherrypy.quickstart(HelloWorld()) ``` -------------------------------- ### CherryPy Trace Middleware Setup Source: https://ddtrace.readthedocs.io/en/stable/integrations.html Install and configure the CherryPy trace middleware to track request timings. This involves importing TraceMiddleware and creating an instance with a service name. ```python from ddtrace.trace import tracer from ddtrace.contrib.cherrypy import TraceMiddleware ``` ```python traced_app = TraceMiddleware(cherrypy, service="my-cherrypy-app") ``` -------------------------------- ### Install Datadog Instrumentation with ddtrace.auto Source: https://ddtrace.readthedocs.io/en/stable/api.html Use `ddtrace.auto` to install Datadog instrumentation in the runtime when `ddtrace-run` is not an option. Install it as early as possible in your application. ```python # myapp.py import ddtrace.auto # install instrumentation as early as possible import mystuff def main(): print("It's my app!") main() ``` -------------------------------- ### Local Installation from Source Source: https://ddtrace.readthedocs.io/en/stable/build_system.html Builds and installs the library in the current Python environment from a local repository using pip. This is the simplest method for local development and testing. ```bash pip install . ``` -------------------------------- ### Start Testagent Service Source: https://ddtrace.readthedocs.io/en/stable/contributing-testing.html Start the testagent service using Docker Compose. This is necessary if your tests rely on the testagent and are encountering 404 errors. ```bash # outside of the testrunner shell $ docker compose up -d testagent # inside the testrunner shell, started with scripts/ddtest $ DD_AGENT_PORT=9126 riot -v run --pass-env ... ``` -------------------------------- ### Install and Use VizTracer for Profiling Source: https://ddtrace.readthedocs.io/en/stable/benchmarks.html Install viztracer and use its tools to view, analyze, and combine profiling data generated from benchmarks. This includes loading specific scenario traces or flamegraphs. ```bash # Install viztracer pip install -U viztracer ``` ```bash # Load a specific scenario in your browser vizviewer artifacts////viztracer/.json ``` ```bash # Load a flamegraph of a specific scenario vizviewer --flamegraph artifacts////viztracer/.json ``` ```bash # Combine all processes/threads into a single flamegraph jq '{"traceEvents": [.traceEvents[] | .pid = "1" | .tid = "1"]}' .json > combined.json vizviewer --flamegraph combined.json ``` -------------------------------- ### Install Library in Development Mode Source: https://ddtrace.readthedocs.io/en/stable/build_system.html Use this command to install the library in editable mode, reflecting source code changes immediately. Ensure you are in the repository's root directory. ```bash pip install -e . ``` -------------------------------- ### Install sccache Source: https://ddtrace.readthedocs.io/en/stable/build_system.html Install sccache using cargo to accelerate compilation of native extensions. This is recommended for frequent rebuilds or multi-container deployments. ```bash cargo install sccache ``` -------------------------------- ### Install Rust Toolchain Source: https://ddtrace.readthedocs.io/en/stable/build_system.html Installs the Rust toolchain (rustc and cargo) using the official installation script. This is required for building Rust-based native extensions. ```bash curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- --default-toolchain stable -y ``` -------------------------------- ### Install OTLP Exporter Source: https://ddtrace.readthedocs.io/en/stable/api.html Install the OpenTelemetry OTLP exporter, which is required for emitting logs in OTLP format. Ensure you are using a minimum supported version. ```bash pip install opentelemetry-exporter-otlp>=1.15.0 ``` -------------------------------- ### Basic Tornado Web Server Setup Source: https://ddtrace.readthedocs.io/en/stable/integrations.html Sets up a basic Tornado web application with a root handler. A request root span is automatically created when any RequestHandler is hit. ```python import asyncio import tornado.web import tornado.httpserver class MainHandler(tornado.web.RequestHandler): def get(self): self.write("Hello, world") async def main(): app = tornado.web.Application([ (r"/", MainHandler), ]) server = tornado.httpserver.HTTPServer(app) server.listen(8888) # Let the asyncio loop run forever await asyncio.Event().wait() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Install ddtrace with pip Source: https://ddtrace.readthedocs.io/en/stable/installation_quickstart.html Install the ddtrace Python library using pip. Ensure you are using pip version 18 or above. ```bash pip install ddtrace ``` -------------------------------- ### Import Datadog Configuration Source: https://ddtrace.readthedocs.io/en/stable/integrations.html Example of importing the Datadog tracing configuration object in Python. ```python from ddtrace import config ``` -------------------------------- ### Install Build Dependencies with Pip Source: https://ddtrace.readthedocs.io/en/stable/build_system.html Installs the specified build dependencies using pip. This command ensures that cython, cmake, and setuptools-rust are available in the current Python environment. ```bash pip install 'cython' 'cmake>=3.24.2,<3.28' 'setuptools-rust<2' ``` -------------------------------- ### Example Fuzzer Directory Structure Source: https://ddtrace.readthedocs.io/en/stable/contributing-fuzzing.html This shows the typical file structure for a fuzzer, including build scripts and source files. ```text ddtrace/internal/datadog/profiling/stack/fuzz/ ├── build.sh ├── fuzz_echion_remote_read.cpp └── CMakeLists.txt ``` -------------------------------- ### Use Consul Client Source: https://ddtrace.readthedocs.io/en/stable/integrations.html Example of using the Consul client after the integration has been patched. ```python client = consul.Consul(host="127.0.0.1", port=8500) client.get("my-key") ``` -------------------------------- ### Manual Flask Tracing Setup Source: https://ddtrace.readthedocs.io/en/stable/integrations.html Import ddtrace.auto and configure your Flask application for manual tracing. This is useful when you need fine-grained control over your tracing setup. ```python import ddtrace.auto from flask import Flask app = Flask(__name__) @app.route('/') def index(): return 'hello world' if __name__ == '__main__': app.run() ``` -------------------------------- ### Integration Test Suite Configuration Example Source: https://ddtrace.readthedocs.io/en/stable/contributing-integrations.html An example configuration for an integration's test suite in `suitespec.yml`. This defines parallelism, monitored paths, runner, snapshot behavior, and required services. ```yaml asyncpg: parallelism: 2 paths: - '@bootstrap' - '@core' - '@contrib' - '@tracing' - '@pg' - tests/contrib/asyncpg/* - tests/snapshots/tests.{suite}.* - tests/contrib/shared_tests_async.py runner: riot snapshot: true services: - postgres ``` -------------------------------- ### Serve ASGI Application with ddtrace-run Source: https://ddtrace.readthedocs.io/en/stable/integrations.html After configuring the TraceMiddleware, use the `ddtrace-run` command to serve your ASGI application and ensure traces are collected. This example uses Uvicorn. ```bash ddtrace-run uvicorn app:app ``` -------------------------------- ### Example: Linux Debug Symbol Zip Name Source: https://ddtrace.readthedocs.io/en/stable/debug_symbols.html Provides a concrete example of a debug symbol zip file name for a Linux wheel. This shows how the general naming convention applies in practice. ```text ddtrace-1.20.0-cp39-cp39-linux_x86_64.whl → ddtrace-1.20.0-cp39-cp39-linux_x86_64-debug-symbols.zip ``` -------------------------------- ### Installing OTLP Exporter for OpenTelemetry Metrics Source: https://ddtrace.readthedocs.io/en/stable/api.html Installs the necessary OpenTelemetry OTLP exporter package. This is a prerequisite for enabling and using OpenTelemetry metrics with `dd-trace-py`, allowing metrics to be sent to OTLP-compatible receivers. ```bash pip install opentelemetry-exporter-otlp>=1.15.0 ``` -------------------------------- ### Running Integration Tests Source: https://ddtrace.readthedocs.io/en/stable/contributing-integrations.html Commands to set up the test environment and run the integration tests. This includes starting Docker containers and executing the `riot` test runner. ```bash $ docker compose up -d testagent $ scripts/ddtest > DD_AGENT_PORT=9126 riot -v run --pass-env ``` -------------------------------- ### Enable Sanic Tracing Explicitly Source: https://ddtrace.readthedocs.io/en/stable/integrations.html Explicitly enable Sanic tracing by importing ddtrace.auto. This example also shows a basic Sanic app setup. ```python import ddtrace.auto from sanic import Sanic from sanic.response import text app = Sanic(__name__) @app.route('/') def index(request): return text('hello world') if __name__ == '__main__': app.run() ``` -------------------------------- ### Geent Context Propagation Example Source: https://ddtrace.readthedocs.io/en/stable/integrations.html Demonstrates how the tracing context is propagated across gevent greenlets. Ensure `tracer` is initialized. ```python def my_parent_function(): with tracer.trace("web.request") as span: span.service = "web" gevent.spawn(worker_function) def worker_function(): # then trace its child with tracer.trace("greenlet.call") as span: span.service = "greenlet" ... with tracer.trace("greenlet.child_call") as child: ... ``` -------------------------------- ### Enable Tracing with ddtrace-run Source: https://ddtrace.readthedocs.io/en/stable/installation_quickstart.html Start your Python application with `ddtrace-run` and configure tracing by setting environment variables for service name, environment, and version. ```bash DD_SERVICE= DD_ENV= DD_VERSION= ddtrace-run python app.py ``` -------------------------------- ### Copy Integration Template Source: https://ddtrace.readthedocs.io/en/stable/contributing-integrations.html Use this command to copy the skeleton integration module to start developing a new integration. ```bash cp -r templates/integration ddtrace/contrib/internal/ ``` -------------------------------- ### Install C++ Build Tools on Ubuntu Source: https://ddtrace.readthedocs.io/en/stable/build_system.html Installs essential C++ build tools (build-essential and cmake) on Ubuntu systems. This is necessary for compiling C++ native extensions. ```bash sudo apt-get install build-essential cmake ``` -------------------------------- ### Enable OpenTelemetry Logs Source: https://ddtrace.readthedocs.io/en/stable/api.html Enable OpenTelemetry logs support by setting the DD_LOGS_OTEL_ENABLED environment variable to true and installing the OTLP exporter. ```APIDOC ## Enable OpenTelemetry Logs ### Description Enable OpenTelemetry logs support by setting `DD_LOGS_OTEL_ENABLED=true` and using `ddtrace.auto` or `ddtrace-run`. `ddtrace` automatically configures the appropriate providers and exporters. You must install an OTLP exporter (minimum supported version: `v1.15.0`). ### Installation ```bash pip install opentelemetry-exporter-otlp>=1.15.0 ``` ### Usage Example ```python import os import logging os.environ["DD_LOGS_OTEL_ENABLED"] = "true" os.environ["DD_TRACE_OTEL_ENABLED"] = "true" import ddtrace.auto from opentelemetry import trace tracer = trace.get_tracer(__name__) # Logs within a trace context are automatically correlated with tracer.start_as_current_span("user_operation") as span: span.set_attribute("user.id", "12345") logging.info("User operation started", extra={"operation": "login"}) # Your business logic here logging.info("User operation completed", extra={"status": "success"}) ``` ``` -------------------------------- ### Install CMake and Xcode Command Line Tools on macOS Source: https://ddtrace.readthedocs.io/en/stable/build_system.html Installs cmake and the Xcode command line tools on macOS. These are required for building C++ native extensions on macOS. ```bash brew install cmake xcode-select --install ``` -------------------------------- ### uWSGI Configuration with INI File Source: https://ddtrace.readthedocs.io/en/stable/advanced_usage.html Configure uWSGI using an INI file for Datadog tracing. This example shows essential settings like module, http, processes, and required Datadog options including 'enable-threads', 'lazy-apps', and 'import'. The 'skip-atexit' option is commented out, indicating its use for uWSGI versions prior to 2.0.30. ```ini ;; uwsgi.ini [uwsgi] module = wsgi:app http = 127.0.0.1:8000 master = true processes = 5 ;; ddtrace required options enable-threads = 1 lazy-apps = 1 skip-atexit = 1 ; For uwsgi<2.0.30 import=ddtrace.bootstrap.sitecustomize ``` -------------------------------- ### ddtrace.auto Source: https://ddtrace.readthedocs.io/en/stable/api.html Importing `ddtrace.auto` installs Datadog instrumentation in the runtime. It should be used when ddtrace-run is not an option. ```APIDOC ## ddtrace.auto ### Description Installs Datadog instrumentation in the runtime. Use when `ddtrace-run` is not an option. ### Usage ```python import ddtrace.auto ``` ``` -------------------------------- ### Example: macOS Debug Symbol Zip Name Source: https://ddtrace.readthedocs.io/en/stable/debug_symbols.html Provides a concrete example of a debug symbol zip file name for a macOS wheel. This demonstrates the naming convention for macOS debug symbol packages. ```text ddtrace-1.20.0-cp39-cp39-macosx_10_9_x86_64.whl → ddtrace-1.20.0-cp39-cp39-macosx_10_9_x86_64-debug-symbols.zip ``` -------------------------------- ### Debug tracing in Kubernetes with IPython Source: https://ddtrace.readthedocs.io/en/stable/advanced_usage.html When running in Kubernetes, ensure your application can reach the tracing Agent. This example demonstrates testing connectivity and debugging tracing by running IPython with debug mode enabled. ```bash $ pip install ipython $ DD_TRACE_DEBUG=true ddtrace-run ipython ``` -------------------------------- ### Import ddtrace.profiling.auto for Automatic Profiling Source: https://ddtrace.readthedocs.io/en/stable/basic_usage.html Import this module to automatically start capturing CPU profiling information. No further configuration is needed for basic CPU profiling. ```python import ddtrace.profiling.auto ``` -------------------------------- ### Sample Flask App with Traced Cache Source: https://ddtrace.readthedocs.io/en/stable/integrations.html A complete example of a Flask application using a traced cache instance obtained from `get_traced_cache`. ```python from flask import Flask from ddtrace.contrib.flask_cache import get_traced_cache app = Flask(__name__) # get the traced Cache class Cache = get_traced_cache(service='my-flask-cache-app') ``` -------------------------------- ### Enable and Use OpenTelemetry Logs with ddtrace Source: https://ddtrace.readthedocs.io/en/stable/api.html Enable OpenTelemetry logs support by setting environment variables and importing ddtrace.auto. This example demonstrates how logs within a trace context are automatically correlated. ```python import os import logging os.environ["DD_LOGS_OTEL_ENABLED"] = "true" os.environ["DD_TRACE_OTEL_ENABLED"] = "true" import ddtrace.auto from opentelemetry import trace tracer = trace.get_tracer(__name__) # Logs within a trace context are automatically correlated with tracer.start_as_current_span("user_operation") as span: span.set_attribute("user.id", "12345") logging.info("User operation started", extra={"operation": "login"}) # Your business logic here logging.info("User operation completed", extra={"status": "success"}) ``` -------------------------------- ### Automatic Span Parenting Example Source: https://ddtrace.readthedocs.io/en/stable/api.html Demonstrates how child spans automatically inherit their parent's context, and how the active span is managed. ```python parent = tracer.trace("parent") # has no parent span assert tracer.current_span() is parent child = tracer.trace("child") assert child.parent_id == parent.span_id assert tracer.current_span() is child child.finish() # parent is now the active span again assert tracer.current_span() is parent parent.finish() assert tracer.current_span() is None parent2 = tracer.trace("parent2") assert parent2.parent_id is None parent2.finish() ``` -------------------------------- ### Integrate Algoliasearch with Datadog Tracing Source: https://ddtrace.readthedocs.io/en/stable/integrations.html Add tracing to your Algolia searches by importing ddtrace.auto and initializing the Algoliasearch client. This example shows how to set up the client and perform a search with specific attributes retrieved. ```python import ddtrace.auto from algoliasearch import algoliasearch client = alogliasearch.Client(, ) index = client.init_index() index.search("your query", args={"attributesToRetrieve": "attribute1,attribute1"}) ``` -------------------------------- ### Configure Logging Format for Trace Correlation Source: https://ddtrace.readthedocs.io/en/stable/integrations.html Set up a logging format that includes Datadog trace attributes. This example demonstrates how to include service, environment, version, trace ID, and span ID in the log format. ```python import logging from ddtrace.trace import tracer FORMAT = ('%(asctime)s %(levelname)s [%(name)s] [%(filename)s:%(lineno)d] ') '[dd.service=%(dd.service)s dd.env=%(dd.env)s ') 'dd.version=%(dd.version)s ') 'dd.trace_id=%(dd.trace_id)s dd.span_id=%(dd.span_id)s] ') '- %(message)s') logging.basicConfig(format=FORMAT) log = logging.getLogger() log.level = logging.INFO @tracer.wrap() def hello(): log.info('Hello, World!') hello() ``` -------------------------------- ### Analyze VizTracer Profile Data with SQL Source: https://ddtrace.readthedocs.io/en/stable/benchmarks.html Query profiling data collected by viztracer using SQL. This example demonstrates how to aggregate trace information, such as call counts and durations, for specific function names. ```sql SELECT IMPORT("experimental.slices"); SELECT name, count(*) as calls, sum(dur) as total_duration, avg(dur) as avg_duration, min(dur) as min_duration, max(dur) as max_duration FROM experimental_slice_with_thread_and_process_info WHERE name like '%/ddtrace/%' group by name having calls > 500 order by total_duration desc ``` -------------------------------- ### Run Traced Application with ddtrace Source: https://ddtrace.readthedocs.io/en/stable/build_system.html Execute a traced application from the repository using the ddtrace command module, especially when using an editable or PYTHONPATH install. ```bash python -m ddtrace.commands.ddtrace_run python my_traced_app.py ``` -------------------------------- ### Start a New Root Span Source: https://ddtrace.readthedocs.io/en/stable/api.html Use `tracer.start_span` to create a new root span representing an operation. Ensure all spans are finished to prevent memory leaks and incorrect parenting. ```python span = tracer.start_span("web.request") ``` -------------------------------- ### Enable Runtime Metrics Service Source: https://ddtrace.readthedocs.io/en/stable/api.html Start the Runtime Metrics service manually. This is an alternative to setting the DD_RUNTIME_METRICS_ENABLED environment variable when using ddtrace-run. ```python from ddtrace.runtime import RuntimeMetrics RuntimeMetrics.enable() ``` -------------------------------- ### Run gunicorn with arguments Source: https://ddtrace.readthedocs.io/en/stable/advanced_usage.html Pass command-line arguments to your application when using `ddtrace-run` with a web server like gunicorn. This example shows how to set max requests and statsd host. ```bash $ ddtrace-run gunicorn myapp.wsgi:application --max-requests 1000 --statsd-host localhost:8125 ``` -------------------------------- ### Enable setuptools instrumentation in setup.py Source: https://ddtrace.readthedocs.io/en/stable/api.html Include a single import statement in your `setup.py` file before importing `setuptools` to automatically enable source code link embedding. ```python import ddtrace.sourcecode.setuptools_auto from setuptools import setup setup( name="mypackage", version="0.0.1", #... ) ``` -------------------------------- ### Configure setuptools build system Source: https://ddtrace.readthedocs.io/en/stable/api.html Add `ddtrace` to your build system requirements in `pyproject.toml` to enable source code integration. ```toml [build-system] requires = ["setuptools", "ddtrace"] build-backend = "setuptools.build_meta" ``` -------------------------------- ### Check pip Version Source: https://ddtrace.readthedocs.io/en/stable/troubleshooting.html Verify the installed version of pip. Ensure pip is version 18 or higher for proper ddtrace installation. ```bash pip --version ``` -------------------------------- ### Compile Native Extensions Source: https://ddtrace.readthedocs.io/en/stable/build_system.html Manually compile native extensions if you skip the pip install -e . command and use PYTHONPATH. This requires build dependencies to be installed first. ```bash python setup.py build_ext --inplace ``` -------------------------------- ### Run and Profile Benchmark Scenario Source: https://ddtrace.readthedocs.io/en/stable/benchmarks.html Compare library versions and generate profiling data using viztracer by setting the `PROFILE_BENCHMARKS=1` environment variable. Results are stored in the artifacts directory. ```bash # Compare and profile PyPI version 2.8.4 against your local changes, and store the results in ./artifacts/ PROFILE_BENCHMARKS=1 scripts/perf-run-scenario span ddtrace==2.8.4 . --artifacts ./artifacts/ ``` -------------------------------- ### Enable Profiling with ddtrace.profiling.auto Source: https://ddtrace.readthedocs.io/en/stable/installation_quickstart.html If `ddtrace-run` is not suitable, enable profiling by importing `ddtrace.profiling.auto`. ```python import ddtrace.profiling.auto ``` -------------------------------- ### Manually Start and Finish a Span Source: https://ddtrace.readthedocs.io/en/stable/basic_usage.html For complete control, manually start a span using `tracer.trace()` and finish it with `span.finish()`. Ensure `span.finish()` is called to send the trace data to Datadog. ```python span = tracer.trace('operations.of.interest') # span is started once created # do some operation(s) of interest in between # NOTE: be sure to call span.finish() or the trace will not be sent to # Datadog span.finish() ``` -------------------------------- ### Enable Tracing with ddtrace.auto Source: https://ddtrace.readthedocs.io/en/stable/installation_quickstart.html Alternatively, enable tracing by importing `ddtrace.auto` as the first line of your application's startup script when `ddtrace-run` cannot be used. ```python import ddtrace.auto ``` -------------------------------- ### uWSGI Configuration with CLI Arguments (>= 2.0.30) Source: https://ddtrace.readthedocs.io/en/stable/advanced_usage.html Use these CLI arguments when configuring uWSGI version 2.0.30 or later for Datadog tracing. Ensure threads are enabled, lazy apps are enabled, and ddtrace is imported. ```bash uwsgi --enable-threads --lazy-apps --import=ddtrace.bootstrap.sitecustomize --master --processes=5 --http 127.0.0.1:8000 --module wsgi:app ``` -------------------------------- ### ddtrace.patch Source: https://ddtrace.readthedocs.io/en/stable/api.html Patch only a set of given modules. Provides granular control over instrumentation setup. ```APIDOC ## ddtrace.patch ### Description Patch only a set of given modules. Provides granular control over instrumentation setup. ### Parameters * **raise_errors** (_bool_) – Raise error if one patch fail. * **patch_modules** (_dict_) – List of modules to patch. ### Usage ```python from ddtrace import patch patch(psycopg=True, elasticsearch=True) ``` ``` -------------------------------- ### uWSGI Configuration with CLI Arguments (< 2.0.30) Source: https://ddtrace.readthedocs.io/en/stable/advanced_usage.html Use these CLI arguments when configuring uWSGI versions prior to 2.0.30 for Datadog tracing. In addition to enabling threads and lazy apps, ensure 'skip-atexit' is enabled to prevent potential crashes. ```bash uwsgi --enable-threads --lazy-apps --skip-atexit --import=ddtrace.bootstrap.sitecustomize --master --processes=5 --http 127.0.0.1:8000 --module wsgi:app ``` -------------------------------- ### Get Current Trace Context Source: https://ddtrace.readthedocs.io/en/stable/advanced_usage.html Retrieve the context of the currently active trace. Returns None if no trace is active. ```python context = tracer.current_trace_context() ``` -------------------------------- ### Instrument OpenSearch with Datadog Patch Source: https://ddtrace.readthedocs.io/en/stable/integrations.html Enable tracing for OpenSearch using the `patch` function. This requires the `opensearch-py` library and `ddtrace` to be installed. ```python from ddtrace import patch from opensearchpy import OpenSearch patch(elasticsearch=True) os = OpenSearch() os.indices.create(index='books', ignore=400) ``` -------------------------------- ### Configure Custom Context Provider Source: https://ddtrace.readthedocs.io/en/stable/advanced_usage.html Replace the default `contextvars` context provider with a custom implementation by implementing the `ddtrace.trace.BaseContextProvider` interface and configuring the tracer. ```python tracer.configure(context_provider=MyContextProvider()) ``` -------------------------------- ### Instrument Elasticsearch with Default Settings Source: https://ddtrace.readthedocs.io/en/stable/integrations.html Report spans for Elasticsearch operations using default instrumentation. Ensure Elasticsearch is installed and accessible. ```python from elasticsearch import Elasticsearch es = Elasticsearch(port=ELASTICSEARCH_CONFIG['port']) es.indices.create(index='books', ignore=400) ``` -------------------------------- ### RuntimeMetrics.enable() Source: https://ddtrace.readthedocs.io/en/stable/api.html Enables the runtime metrics collection service. If the service is already active, this method does nothing. It can be started automatically by `ddtrace-run` or invoked manually. ```APIDOC ## RuntimeMetrics.enable() ### Description Enables the runtime metrics collection service. This method can be called to manually start the service if it's not automatically started by `ddtrace-run`. ### Method `static enable(_tracer : Optional[ddtrace._trace.tracer.Tracer] = None_, _dogstatsd_url : Optional[str] = None_) -> None` ### Parameters #### Parameters - **tracer** (Optional[ddtrace._trace.tracer.Tracer]) - The tracer instance to correlate with. - **dogstatsd_url** (Optional[str]) - The URL for DogStatsD. ### Request Example ```python from ddtrace.runtime import RuntimeMetrics RuntimeMetrics.enable() ``` ### Response This method does not return a value. ``` -------------------------------- ### Implement libFuzzer Harness Source: https://ddtrace.readthedocs.io/en/stable/contributing-fuzzing.html Write a C/C++ file that implements the libFuzzer interface, specifically the `LLVMFuzzerTestOneInput` function. This function receives fuzzer-generated input and should call the code under test. Handle empty inputs gracefully and return 0 to continue fuzzing. ```cpp // fuzz_your_component.cpp #include #include #include "your_component.h" // Your code to test extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { if (size == 0) { return 0; } // Call your code with fuzzer-generated input your_function_to_test(data, size); return 0; // Continue fuzzing } ``` -------------------------------- ### enable() Source: https://ddtrace.readthedocs.io/en/stable/genindex.html Enables runtime metrics collection. ```APIDOC ## enable() ### Description Enables runtime metrics collection. ### Method static method of ddtrace.runtime.RuntimeMetrics ``` -------------------------------- ### Enable Protobuf Tracing Source: https://ddtrace.readthedocs.io/en/stable/integrations.html Manually enable the Protobuf integration by calling `patch(protobuf=True)` after importing the `patch` function from `ddtrace`. ```python from ddtrace import patch patch(protobuf=True) ``` -------------------------------- ### Patch Jinja2 Integration Source: https://ddtrace.readthedocs.io/en/stable/integrations.html Manually enable the Jinja2 integration for tracing template operations. Ensure Jinja2 is installed and the templates directory is correctly configured. ```python from ddtrace import patch from jinja2 import Environment, FileSystemLoader patch(jinja2=True) env = Environment( loader=FileSystemLoader("templates") ) template = env.get_template('mytemplate.html') ``` -------------------------------- ### Configure HTTP Client Query String Tracing Source: https://ddtrace.readthedocs.io/en/stable/advanced_usage.html Enable tracing of the URL query string for HTTP client requests. Configuration can be set globally via environment variables or at the integration level. ```python from ddtrace import config # Global config # Set DD_TRACE_HTTP_CLIENT_TAG_QUERY_STRING environment variable to true/false # Integration level config, e.g. 'falcon' config.falcon.http.trace_query_string = True ``` -------------------------------- ### Enabling and Using OpenTelemetry Metrics Source: https://ddtrace.readthedocs.io/en/stable/api.html Enables OpenTelemetry metrics support by setting an environment variable and importing `ddtrace.auto`. This automatically configures Datadog's MeterProvider to emit metrics in OTLP format, which can be sent to any OTLP-compatible receiver. ```python import os os.environ["DD_METRICS_OTEL_ENABLED"] = "true" import ddtrace.auto from opentelemetry import metrics # ddtrace automatically configures the MeterProvider meter = metrics.get_meter(__name__) counter = meter.create_counter("requests_total") counter.add(1, {"method": "GET"}) ``` -------------------------------- ### Enable and Disable Dynamic Instrumentation Programmatically Source: https://ddtrace.readthedocs.io/en/stable/api.html Manually enable and disable dynamic instrumentation. This method requires starting the service in every forked process. ```python from ddtrace.debugging import DynamicInstrumentation # Enable dynamic instrumentation DynamicInstrumentation.enable() ... # Disable dynamic instrumentation DynamicInstrumentation.disable() ``` -------------------------------- ### Configuring Tornado Integration Settings Source: https://ddtrace.readthedocs.io/en/stable/integrations.html Illustrates how to configure Tornado tracing settings, such as `default_service`, `tags`, and `distributed_tracing`, directly within the Tornado application settings. ```python settings = { 'datadog_trace': { 'default_service': 'my-tornado-app', 'tags': {'env': 'production'}, 'distributed_tracing': False, }, } app = tornado.web.Application([ (r'/', MainHandler), ], **settings) ``` -------------------------------- ### Component Definition in Suitespec Source: https://ddtrace.readthedocs.io/en/stable/contributing-integrations.html Example of defining a component for an integration within `tests/contrib/suitespec.yml`. This maps a component name to related files for CI test relevance. ```yaml mongo: - ddtrace/contrib/internal/pymongo/* - ddtrace/ext/mongo.py ``` -------------------------------- ### Enable Falcon Autopatching Source: https://ddtrace.readthedocs.io/en/stable/integrations.html Automatically enable tracing for the Falcon framework using the `patch` function. This simplifies integration by avoiding manual middleware setup. ```python import falcon from ddtrace.trace import patch patch(falcon=True) app = falcon.API() ``` -------------------------------- ### Display ddtrace-run help Source: https://ddtrace.readthedocs.io/en/stable/advanced_usage.html Use the `-h` flag to display the help message for `ddtrace-run`, showing its usage and available options. ```bash $ ddtrace-run -h Execute the given Python program, after configuring it to emit Datadog traces. Append command line arguments to your program as usual. Usage: ddtrace-run ``` -------------------------------- ### Compile Release Notes with Reno and Pandoc Source: https://ddtrace.readthedocs.io/en/stable/releasenotes.html Compile all release notes from the beginning of time to a given version using `reno report` and `pandoc`. This command generates release notes in a single text string, ordered from latest to earliest. ```bash pip install reno brew install pandoc git checkout reno report --no-show-source | pandoc -f rst -t gfm --wrap=none | pbcopy ``` -------------------------------- ### Set Log Formatter to UTC Source: https://ddtrace.readthedocs.io/en/stable/advanced_usage.html Ensure log timestamps are in UTC by setting the logging.Formatter.converter to time.gmtime. This is useful for consistent timestamping across different host setups. ```python import time logging.Formatter.converter = time.gmtime ``` -------------------------------- ### Running a Fuzzer with libFuzzer Options Source: https://ddtrace.readthedocs.io/en/stable/contributing-fuzzing.html This command shows how to execute a fuzzer binary with common libFuzzer runtime options. It specifies the corpus directory, maximum total time, maximum input length, and number of parallel jobs. ```bash $ ./fuzzer corpus/ -max_total_time=60 -max_len=4096 -jobs=4 ``` -------------------------------- ### PyTorch CIFAR-10 Training with Profiling Source: https://ddtrace.readthedocs.io/en/stable/advanced_usage.html Example program for CIFAR-10 image classification using PyTorch, instrumented for profiling with ddtrace. This code requires PyTorch 1.8.1 or later. ```python import torch import torch.nn import torch.optim import torch.utils.data import torchvision.datasets import torchvision.models import torchvision.transforms as T from torchvision.models import resnet18, ResNet18_Weights from torch.profiler import ProfilerActivity def cifar(): transform = T.Compose( [T.Resize(224), T.ToTensor(), T.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))] ) train_set = torchvision.datasets.CIFAR10( root="./data", train=True, download=True, transform=transform ) train_loader = torch.utils.data.DataLoader(train_set, batch_size=32, shuffle=True) device = torch.device("cuda") model = resnet18(weights=ResNet18_Weights.DEFAULT).cuda() criterion = torch.nn.CrossEntropyLoss() optimizer = torch.optim.SGD(model.parameters(), lr=0.001, momentum=0.9) model.train() def train(data): inputs, labels = data[0].to(device=device), data[1].to(device=device) outputs = model(inputs) loss = criterion(outputs, labels) optimizer.zero_grad() loss.backward() optimizer.step() with torch.profiler.profile( activities=[ProfilerActivity.CUDA], ): for step, batch_data in enumerate(train_loader): print("step #%d" % step) if step >= (1 + 1 + 3) * 2: break train(batch_data) if __name__ == "__main__": cifar() ``` -------------------------------- ### Configure Fuzz Target with CMake Source: https://ddtrace.readthedocs.io/en/stable/contributing-fuzzing.html Set up the `CMakeLists.txt` file to build the fuzzing target. This includes defining the executable, linking source files, setting include directories, and configuring compiler options for sanitizers if libFuzzer is enabled. ```cmake cmake_minimum_required(VERSION 3.19) add_executable(fuzz_your_component fuzz_your_component.cpp ../src/your_source.c ) target_include_directories(fuzz_your_component PRIVATE ../include) if(STACK_USE_LIBFUZZER) target_compile_options(fuzz_your_component PRIVATE -fsanitize=fuzzer,address,undefined -fno-omit-frame-pointer ) target_link_options(fuzz_your_component PRIVATE -fsanitize=fuzzer,address,undefined ) endif() ``` -------------------------------- ### Enable httplib Tracing with Environment Variable Source: https://ddtrace.readthedocs.io/en/stable/integrations.html Enable the httplib integration by setting the DD_PATCH_MODULES environment variable. This is useful when not using ddtrace-run. ```bash DD_PATCH_MODULES=httplib:true ddtrace-run .... ``` -------------------------------- ### Patch Specific Modules with ddtrace.patch Source: https://ddtrace.readthedocs.io/en/stable/api.html Patch only a set of given modules for more granular control over instrumentation setup. Set `raise_errors` to `True` to raise an error if a patch fails. ```python >>> patch(psycopg=True, elasticsearch=True) ``` -------------------------------- ### Enable Django Tracing with ddtrace-run Source: https://ddtrace.readthedocs.io/en/stable/integrations.html Enable Django tracing automatically by running your application with `ddtrace-run`. ```bash ddtrace-run python manage.py runserver ``` -------------------------------- ### Patch Kombu Integration Source: https://ddtrace.readthedocs.io/en/stable/integrations.html Manually patch the Kombu library to enable tracing. This example shows how to establish a connection, define a queue, and publish a message, with spans reported automatically. ```python from ddtrace import patch # If not patched yet, you can patch kombu specifically patch(kombu=True) # This will report a span with the default settings import kombu conn = kombu.Connection("amqp://guest:guest@127.0.0.1:5672//") conn.connect() task_queue = kombu.Queue('tasks', kombu.Exchange('tasks'), routing_key='tasks') to_publish = {'hello': 'world'} producer = conn.Producer() producer.publish(to_publish, exchange=task_queue.exchange, routing_key=task_queue.routing_key, declare=[task_queue]) ``` -------------------------------- ### Tracer.configure Source: https://ddtrace.readthedocs.io/en/stable/api.html Configure a Tracer. Allows customization of context providers, error handling, and feature enablement. ```APIDOC ## Tracer.configure ### Description Configure a Tracer. Allows customization of context providers, error handling, and feature enablement. ### Parameters * **context_provider** (_object_) – The `ContextProvider` that will be used to retrieve automatically the current call context. * **compute_stats_enabled** (_bool_) – Enables or disables computation of statistics. * **appsec_enabled** (_bool_) – Enables Application Security Monitoring (ASM) for the tracer. * **appsec_enabled_origin** (_str_) – Specifies the origin for ASM enablement. * **iast_enabled** (_bool_) – Enables IAST support for the tracer. * **apm_tracing_disabled** (_bool_) – When APM tracing is disabled ensures ASM support is still enabled. * **trace_processors** (_list[TraceProcessor]_ ) – Trace processors are used to modify and filter traces based on certain criteria. ### Usage ```python from ddtrace.trace import tracer tracer.configure( appsec_enabled=True, iast_enabled=False ) ``` ``` -------------------------------- ### Control Profiling with ddtrace.profiling.Profiler API Source: https://ddtrace.readthedocs.io/en/stable/basic_usage.html Use the Profiler object to manually start and stop profiling. This provides fine-grained control over the profiler's lifecycle, but avoid frequent start/stop cycles. ```python from ddtrace.profiling import Profiler prof = Profiler() prof.start() # At shutdown prof.stop() ``` -------------------------------- ### Recreate Virtual Environments for Riot Tests Source: https://ddtrace.readthedocs.io/en/stable/troubleshooting.html Use this command to remove all riot virtual environments and re-create them, which can resolve ModuleNotFoundError issues during testing. It ensures packages are installed in the correct virtual environments. ```bash scripts/ddtest DD_TRACE_AGENT_URL=http://localhost:9126 riot -v run -p3.12 --pass-env ``` -------------------------------- ### Test Fuzzer Locally Source: https://ddtrace.readthedocs.io/en/stable/contributing-fuzzing.html Execute the fuzzing harness locally to verify the build and initial functionality. This can be done using Docker for a consistent environment or by directly running the compiled binary after executing the `build.sh` script. ```bash cd path/to/your/component/fuzz/ ./build.sh /tmp/fuzz/build/your_component/fuzz_your_component -max_total_time=60 ``` -------------------------------- ### Set Datadog Site Source: https://ddtrace.readthedocs.io/en/stable/configuration.html Specify the Datadog site for uploading profiles and logs. Use 'datadoghq.eu' for the EU site. ```bash DD_SITE=datadoghq.eu ``` -------------------------------- ### Get Local Root Span with `current_root_span` Source: https://ddtrace.readthedocs.io/en/stable/api.html Retrieve the local root span for the current execution context. This is useful for attaching information to the primary span of the current process, such as setting a 'host' tag. ```python # get the local root span local_root_span = tracer.current_root_span() # set the host just once on the root span if local_root_span: local_root_span.set_tag('host', '127.0.0.1') ``` -------------------------------- ### Configure Benchmark Scenario Variables Source: https://ddtrace.readthedocs.io/en/stable/benchmarks.html Specify configuration variables for a benchmark scenario using YAML. This allows defining different sets of parameters for the same scenario. ```yaml small-size: size: 10 large-size: size: 1000 huge-size: size: 1000000 ``` -------------------------------- ### Running uWSGI with INI File Source: https://ddtrace.readthedocs.io/en/stable/advanced_usage.html This command executes uWSGI using the specified INI configuration file. ```bash uwsgi --ini uwsgi.ini ``` -------------------------------- ### Configuring Datadog Logger Level in Python Source: https://ddtrace.readthedocs.io/en/stable/advanced_usage.html Control the verbosity of Datadog's internal logs by setting the 'ddtrace' logger level. This example sets the root logger to DEBUG and the 'ddtrace' logger to WARNING, reducing Datadog's log output when verbose logging is active globally. ```python logging.getLogger().setLevel(logging.DEBUG) logging.getLogger("ddtrace").setLevel(logging.WARNING) ``` -------------------------------- ### Submit Ray Job with Metadata Source: https://ddtrace.readthedocs.io/en/stable/integrations.html Submit a Ray job with custom metadata to define the service name. ```bash ray job submit --metadata-json='{"job_name": "my_model"}' -- python entrypoint.py ``` -------------------------------- ### Run Benchmark Scenario Comparison Source: https://ddtrace.readthedocs.io/en/stable/benchmarks.html Execute a benchmark scenario comparing two versions of the ddtrace library. Results are saved to a local artifacts folder. Version specifiers can be PyPI versions, git repositories, or local paths. ```bash scripts/perf-run-scenario --artifacts ``` ```bash # Compare PyPI versions 0.50.0 vs 0.51.0 scripts/perf-run-scenario span ddtrace==0.50.0 ddtrace==0.51.0 --artifacts ./artifacts/ ``` ```bash # Compare PyPI version 0.50.0 vs your local changes scripts/perf-run-scenario span ddtrace==0.50.0 . --artifacts ./artifacts/ ``` ```bash # Compare git branch 1.x vs git branch my-feature scripts/perf-run-scenario span Datadog/dd-trace-py@1.x Datadog/dd-trace-py@my-feature --artifacts ./artifacts/ ``` ```bash # Run benchmark on a single version without comparison scripts/perf-run-scenario span ddtrace==0.51.0 "" --artifacts ./artifacts/ ``` -------------------------------- ### Generate Release Notes Source: https://ddtrace.readthedocs.io/en/stable/contributing-release.html Checkout the relevant branch, fetch updates, and use 'reno report' to generate release notes. Pipe the output to pandoc for formatting and then to 'less' for viewing. This process is typically done on the x.y release branch. ```bash $ git checkout $ git fetch $ reno report --branch=origin/ | pandoc -f rst -t gfm --wrap=none | less ``` -------------------------------- ### GDB: Setting Substitute Paths for Source Code Source: https://ddtrace.readthedocs.io/en/stable/debug_symbols.html Configure GDB to map build paths to actual source code directories using the 'set substitute-path' command. This is crucial for displaying source code alongside assembly. ```gdb (gdb) set substitute-path /project/build/cmake.linux-x86_64-cpython-313/ddtrace.internal.datadog.profiling.stack_v2._stack_v2/_deps/echion-src/echion /path/to/echion/source/code ```