Registry / observability / opencensus-ext-logging

opencensus-ext-logging

JSON →
library0.1.1pypypi✓ verified 22d ago

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.

pip install opencensus-ext-logging
INSTALL
IMPORT
SIG · OPENCENSUS-EXT-LOG
O
opencensus-ext-logging
observabilitypythonv0.1.1
Install
4.3s avg
Import
211ms
Disk
49MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v0.1.1 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.330s · 49.3MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 4.3s · import 0.092s · 50MB
49MB installed
● package 49MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

config_integration
from opencensus.trace import config_integration

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.")
Debug
Known issues
breakingThe OpenCensus project, including `opencensus-ext-logging`, has been officially deprecated in favor of OpenTelemetry. OpenCensus will no longer receive new features or security updates, and users are strongly encouraged to migrate.
fix
Migrate to OpenTelemetry using its Python SDK and relevant instrumentation. OpenTelemetry provides bridges for incremental migration.
affects: All versions
deprecatedOpenCensus Azure Monitor exporters, which commonly leverage `opencensus-ext-logging` for log correlation, are also deprecated and will be officially unsupported by September 2024.
fix
Migrate to the Azure Monitor OpenTelemetry Distro or the Azure Monitor OpenTelemetry exporters for continued support.
affects: All versions
gotchaThe `opencensus-ext-logging` integration only affects Python `logging` instances created *after* `config_integration.trace_integrations(['logging'])` has been called. Loggers initialized before this configuration will not be enriched.
fix
Call `config_integration.trace_integrations(['logging'])` at the very beginning of your application startup, before any loggers you wish to instrument are instantiated.
affects: All versions
gotchaWhen using `opencensus-ext-logging` in conjunction with certain `logging.Handler` implementations (e.g., `AzureLogHandler` from `opencensus-ext-azure`), there have been reports of recursive logging issues, which can lead to excessive logging or application crashes.
fix
If encountering recursive logging with `AzureLogHandler`, try initializing it with `enable_local_storage=False`. The recommended long-term solution is to migrate to OpenTelemetry.
affects: Likely older versions, but possible with 0.1.1.
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'opencensus-ext-logging'
This error occurs when the `opencensus-ext-logging` package has not been installed or is not accessible in the Python environment where the code is being run.
fix
Install the package using pip: `pip install opencensus-ext-logging`
Logs not showing traceId or spanId / Logging not enriched with trace information
The logging integration was not configured before the loggers were instantiated, meaning existing loggers were not affected.
fix
Ensure `config_integration.trace_integrations(['logging'])` is called at the very beginning of your application startup, before any loggers you wish to instrument are created. 
```python
import logging
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

# This must be done *before* loggers are created
config_integration.trace_integrations(['logging'])

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)


with tracer_module.Tracer(sampler=AlwaysOnSampler(), exporter=PrintExporter()) as tracer:
    with tracer.span(name='my_span'):
        logger.info('This log should have trace and span IDs.')
```
Recursive logging issue / excessive logging with AzureLogHandler
When `opencensus-ext-logging` is used with `AzureLogHandler` from `opencensus-ext-azure`, a circular logging issue can occur where failed log transmissions are retried indefinitely, leading to excessive logging or application crashes.
fix
Initialize `AzureLogHandler` with `enable_local_storage=False` to prevent this behavior. Alternatively, consider migrating to OpenTelemetry as OpenCensus is deprecated. 
```python
import logging
from opencensus.ext.azure.log_exporter import AzureLogHandler
from opencensus.trace import config_integration

# Configure logging integration
config_integration.trace_integrations(['logging'])

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)

# Initialize AzureLogHandler with enable_local_storage=False
handler = AzureLogHandler(connection_string='InstrumentationKey=<your-instrumentation-key>', enable_local_storage=False)
logger.addHandler(handler)

logger.info('Test log to Azure Monitor.')
```
Info logs not appearing in Application Insights / Missing lower level logs
The Python `logging` module's default root logger level or the `AzureLogHandler`'s level might be set to `WARNING` or higher, filtering out `INFO` or `DEBUG` level messages before they are processed by the exporter.
fix
Explicitly set the logging level of your logger and/or the `AzureLogHandler` to `INFO` or `DEBUG` to ensure lower-level logs are processed. 
```python
import logging
from opencensus.ext.azure.log_exporter import AzureLogHandler

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO) # Set the logger level to INFO or DEBUG

handler = AzureLogHandler(connection_string='InstrumentationKey=<your-instrumentation-key>')
handler.setLevel(logging.INFO) # Optionally, set the handler level
logger.addHandler(handler)

logger.debug('This is a debug message.')
logger.info('This is an info message.')
logger.warning('This is a warning message.')
```
Upgrade
Version history
0.1.1latest on PyPI · released Oct 5, 2021
Audit
Dependencies
opencensusrequiredProvides the core tracing context and `config_integration` functionality.
Agent activity
32 hits · last 30 days
node
26
OpenAI (training)
2
Resources