pythonazureazure-functionsazure-application-insights

Writing to application insights from an azure python function app using opentelemetry


So I created a function app and logging works as expected, writing entries to application insights. But as I need custom dimensions I included opentelemetry. However I get no logging send to application insigths, and no errors. Any pointers?

function_app.py:

import datetime
import logging
import azure.functions as func
from azure.identity import DefaultAzureCredential,ManagedIdentityCredential
from azure.storage.blob import BlobClient, BlobServiceClient, ContainerClient
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import trace

logger = logging.getLogger(__name__)

credential = DefaultAzureCredential()
configure_azure_monitor(
    credential=credential,
)

tracer = trace.get_tracer(__name__)

app = func.FunctionApp()

@app.timer_trigger(schedule="0 0 10 * * *", arg_name="myTimer", run_on_startup=True, use_monitor=False) 
def timer_trigger(myTimer: func.TimerRequest) -> None:

     with tracer.start_as_current_span("hello with aad managed identity"):
          
          logger.warning("Warning sent")
          
          properties = {'custom_dimensions': {'key_1': 'value_1', 'key_2': 'value_2'}}
          logging.warning('Warning with props', extra=properties)

local.settings.json:

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "",
    "FUNCTIONS_WORKER_RUNTIME": "python",
    "APPLICATIONINSIGHTS_CONNECTION_STRING":"InstrumentationKey=xx-xx-xx-xx-xx;IngestionEndpoint=https://westeurope-5.in.applicationinsights.azure.com/;LiveEndpoint=https://westeurope.livediagnostics.monitor.azure.com/;ApplicationId=xx-xx-xx-xx-xx"
  }
}

Solution

  • When you are using configure_azure_monitor and start_as_current_span check logs and code it correctly as below:

    Used http trigger here, you can replace it with timer trigger:

    import azure.functions as cho
    from azure.monitor.opentelemetry import configure_azure_monitor
    from opentelemetry import trace
    
    tt = cho.FunctionApp(http_auth_level=cho.AuthLevel.ANONYMOUS)
    
    @tt.route(route="http_trigger")
    def http_trigger(req: cho.HttpRequest) -> cho.HttpResponse:
        configure_azure_monitor(connection_string="InstrumentationKey=fade05c1e02;IngestionEndpoint=https://eastus-8.in.applicationinsights.azure.com/;LiveEndpoint=https://eastus.livediagnostics.monitor.azure.com/;ApplicationId=a65c7d7c8c4b1")
        ri_ch = trace.get_tracer(__name__)
        with ri_ch.start_as_current_span("This is a Log") as val:
            val.set_attribute("who", "rithwik")
            print("Hello Rithwik Bojja, the logs are Logged")
            return cho.HttpResponse("This HTTP triggered function executed successfully.",status_code=200)
    

    Output:

    dependencies
    | project name, customDimensions
    

    enter image description here

    To add more attributed use val.set_attribute().