OpenCensus Logging Integration

0.1.1 · deprecated · verified Sun Apr 12

This library provides an integration for the OpenCensus tracing framework with Python's standard `logging` module. It enriches standard log records with `traceId`, `spanId`, and `traceSampled` attributes, enabling correlation of application logs with distributed traces. The current version is 0.1.1. The OpenCensus project is largely deprecated in favor of OpenTelemetry, with official support for some related exporters (e.g., Azure Monitor) ending by September 2024.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to enable the OpenCensus logging integration and how log messages are enriched with `traceId` and `spanId` when an OpenCensus trace span is active. The `PrintExporter` is used to visualize the trace information, and the standard Python logging handler outputs the enriched log records.

import logging
import os
from opencensus.trace import config_integration
from opencensus.trace import tracer as tracer_module
from opencensus.trace.exporters import PrintExporter
from opencensus.trace.samplers import AlwaysOnSampler

# 1. Configure the logging integration
# This must be done *before* loggers are created for existing loggers to be affected.
config_integration.trace_integrations(['logging'])

# 2. Set up a basic Python logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
handler = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - TraceId: %(traceId)s - SpanId: %(spanId)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)

# 3. Set up an OpenCensus tracer with an exporter (e.g., PrintExporter)
# This will activate trace context, making trace and span IDs available for logging.
exporter = PrintExporter()
sampler = AlwaysOnSampler()
tracer = tracer_module.Tracer(exporter=exporter, sampler=sampler)

logger.info("This log message will not have trace/span IDs yet as no span is active.")

# 4. Use the tracer to create a span to enable trace context propagation
with tracer.span(name='my_operation') as span:
    logger.info("This log message should now have trace and span IDs.")
    with tracer.span(name='sub_operation'):
        logger.warning("Another log message within a sub-span.")

logger.info("This log message is outside the span and will not have trace/span IDs from the active span.")

view raw JSON →