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

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

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 opencensus.ext.azure.log_exporter import AzureLogHandler
 
logger = logging.getLogger(__name__)
# TODO: replace the all-zero GUID with your instrumentation key.
logger.addHandler(AzureLogHandler(
    connection_string='InstrumentationKey=00000000-0000-0000-0000-000000000000')
)
 
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 opencensus.ext.azure.trace_exporter 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
 
config_integration.trace_integrations(['requests'])
 
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='http://example.com')
    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: https://github.com/census-instrumentation/opencensus-python/tree/master/contrib/opencensus-ext-azure...

 

Hope this helps!

Shashank Ranjan

Azure App Services Support Engineering

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