OpenCensus Runtime Context
OpenCensus Runtime Context is a Python library that provides in-process context propagation, using `contextvars` for Python 3.6+ (with asyncio support) and thread-local storage for older Python versions (2.7, 3.4, 3.5). While the `opencensus-python` repository still exists, the broader OpenCensus project has merged with OpenTracing to form OpenTelemetry, which is now the recommended successor for observability. This library's last release was in August 2022, version 0.1.3. [1, 2, 3, 9]
Warnings
- breaking OpenCensus has officially merged with OpenTracing to form OpenTelemetry, which is considered the next major version. Users are strongly encouraged to migrate to OpenTelemetry for active development, new features, and continued support. Most OpenCensus GitHub repositories (except `opencensus-python`) were archived on July 31st, 2023. [3, 9, 10, 12]
- deprecated Azure Monitor OpenCensus exporters are on the path to deprecation and will be officially unsupported by September 2024. Users are advised to migrate to Azure Monitor OpenTelemetry Distro or exporters. [14]
- gotcha `opencensus-context` uses `contextvars` for Python 3.6+ for asyncio support and thread-local storage for older Python versions (2.7, 3.4, 3.5). This might lead to unexpected behavior if not accounted for when porting code between Python versions, especially with asynchronous patterns. [1, 2]
- breaking OpenTelemetry-based monitoring for Python officially supports Python 3.7 and later. If you are using OpenCensus with Python 2.7, 3.4, 3.5, or 3.6, you will need to upgrade your Python version to migrate to OpenTelemetry-based solutions, as these older Python versions are end-of-life and unsupported by OpenTelemetry. [16]
Install
-
pip install opencensus-context
Imports
- RuntimeContext
from opencensus.common.runtime_context import RuntimeContext
Quickstart
from threading import Thread
from opencensus.common.runtime_context import RuntimeContext
def work(name):
# The context is automatically propagated to new threads started via with_current_context
current_context = RuntimeContext.current_context()
print(f"Worker '{name}' in context: {current_context}")
# Create a context on the main thread
RuntimeContext.current_context()['request_id'] = 'main_req_123'
# Propagate context explicitly to a new thread
thread = Thread(
target=RuntimeContext.with_current_context(work),
args=('child_thread_A',),
)
thread.start()
thread.join()
# Another example with a simple function call in the current context
def another_work(name):
current_context = RuntimeContext.current_context()
print(f"Another worker '{name}' in context: {current_context}")
another_work('direct_call_B')