How to implement OpenCensus to send custom dimensions to AI in Python?

Published 03-12-2021 12:32 AM 2,788 Views

With Python application, you can use OpenCensus to send the telemetry data. However, if your requirement is to use custom dimensions, you can use as below:


import logging
from import AzureLogHandler
logger = logging.getLogger(__name__)
# TODO: replace the all-zero GUID with your instrumentation key.
properties = {'custom_dimensions': {'key_1': 'value_1', 'key_2': 'value_2'}}
# Use properties in logging statements
logger.warning('action', extra=properties)



In case, your requirement is to use correlation ID with custom dimensions, Function App does not have the feature available yet. The team is working on a solution to light up this feature.

Until then, use the example below and initialize the OpenCensus component with the correlation id in your function’s trigger.


import json
import logging
import requests
import azure.functions as func
from import AzureExporter
from opencensus.trace import config_integration
from opencensus.trace.samplers import ProbabilitySampler
from opencensus.trace.tracer import Tracer
from opencensus.trace import execution_context
from opencensus.trace.propagation.trace_context_http_header_format import TraceContextPropagator
exporter = AzureExporter(instrumentation_key="aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee")
def main(req: func.HttpRequest, context: func.Context) -> func.HttpResponse:
    ## these below four lines
    span_context = TraceContextPropagator().from_headers({"traceparent": context.trace_context.Traceparent, "tracestate": context.trace_context.Tracestate})
    tracer = Tracer(span_context=span_context, exporter=exporter, sampler=ProbabilitySampler(1.0))
    execution_context.set_opencensus_tracer(tracer)  # < -- sets the passed in tracer as the current tracer
    with tracer.span("parent"):
        response = requests.get(url='')
    return json.dumps({
        'method': req.method,
        'ctx_func_name': context.function_name,
        'ctx_func_dir': context.function_directory,
        'ctx_invocation_id': context.invocation_id,
        'ctx_trace_context_Traceparent': context.trace_context.Traceparent,
        'ctx_trace_context_Tracestate': context.trace_context.Tracestate,


Also, check the OpenCensus Azure extension Repository:


Hope this helps!

Shashank Ranjan

Azure App Services Support Engineering

Version history
Last update:
‎Mar 12 2021 01:23 AM
Updated by: