OpenCensus Requests Integration

0.8.0 · maintenance · verified Thu Apr 16

OpenCensus-ext-requests provides integration for the OpenCensus Python library to automatically trace HTTP requests made with the popular 'requests' package. OpenCensus is a set of libraries for collecting application metrics and distributed traces. The current version is 0.8.0. The OpenCensus project is largely in maintenance mode, having merged with OpenTracing to form OpenTelemetry, and users are encouraged to migrate.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to enable the `requests` integration, initialize a basic OpenCensus tracer, and perform an HTTP request. The `PrintExporter` is used to output trace data directly to the console for easy verification. The `config_integration.trace_integrations(['requests'])` call is crucial for automatically instrumenting `requests` calls.

import os
import requests
from opencensus.trace import config_integration
from opencensus.trace.tracer import Tracer
from opencensus.trace.samplers import ProbabilitySampler
from opencensus.trace.exporters import PrintExporter

# Enable the requests integration
config_integration.trace_integrations(['requests'])

# Configure a tracer with a sampler and an exporter
tracer = Tracer(
    sampler=ProbabilitySampler(rate=1.0),
    exporter=PrintExporter()
)

print("Making an HTTP request which will be traced...")
with tracer.span(name='parent_span'):
    # The requests.get call below will be automatically traced
    # and appear as a child span of 'parent_span'.
    # Using a non-existent URL for demonstration, a real URL would work similarly.
    try:
        response = requests.get('http://non-existent-example.com/api/data')
        print(f"Request completed with status: {response.status_code}")
    except requests.exceptions.ConnectionError as e:
        print(f"Connection error: {e}. This is expected for non-existent-example.com")

print("Trace data should have been printed to stdout by PrintExporter.")

view raw JSON →