pythonazureazure-functionsazure-application-insights

Writing to application insights from a Phyton Azure Function App


I am trying to add logs with custom dimensions to the trace table in application insights. I have code below working but it writes to the dependency table. Any pointers how to write to traces and metrics?

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="ai conn str")
    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)

Solution

  • I modified your code to include a logger and attributes for the request to add logs with custom dimensions, capturing both traces and metrics in Application Insights for the function.

        logger.info("Hello Kamali", extra={"custom_dimension": "Kam_value"})
            # Added attributes for the request
            span.set_attribute("http.method", req.method)
            span.set_attribute("http.route", "/http_trigger")
            span.set_attribute("http.status_code", 200)
            span.set_attribute("custom_dimension", "Kam_value")
            span.set_attribute("who", "Kamali")
    

    function_app.py :

    import logging
    import azure.functions as func
    from azure.monitor.opentelemetry import configure_azure_monitor
    from opentelemetry import trace
    from opentelemetry.sdk.trace import TracerProvider
    from opentelemetry.trace import SpanKind
    from opentelemetry.sdk._logs import LoggingHandler
     
    configure_azure_monitor(connection_string="<AppInsightsConneString>")
     
    logger = logging.getLogger(__name__)
    logger.setLevel(logging.INFO)
    handler = LoggingHandler()
    logger.addHandler(handler)
     
    app = func.FunctionApp(http_auth_level=func.AuthLevel.ANONYMOUS)
     
    @app.route(route="http_trigger")
    def http_trigger(req: func.HttpRequest) -> func.HttpResponse:
        """
        Handles the HTTP trigger and logs telemetry to Application Insights.
        """
        logger.info("Hello Kamali", extra={"custom_dimension": "Kam_value"})
        tracer = trace.get_tracer(__name__)
        with tracer.start_as_current_span("HTTP Request", kind=SpanKind.SERVER) as span:
            span.set_attribute("http.method", req.method)
            span.set_attribute("http.route", "/http_trigger")
            span.set_attribute("http.status_code", 200)
            span.set_attribute("custom_dimension", "Kam_value")
            span.set_attribute("who", "Kamali")
        return func.HttpResponse(
            "This HTTP triggered function executed successfully.",
            status_code=200
        )
    

    host.json :

    {
      "version": "2.0",
      "logging": {
        "applicationInsights": {
          "samplingSettings": {
            "isEnabled": true,
            "excludedTypes": ""
          }
        }
      },
      "extensionBundle": {
        "id": "Microsoft.Azure.Functions.ExtensionBundle",
        "version": "[4.*, 5.0.0)"
      }
    }
    

    requirements.txt :

    azure-functions
    azure-monitor-opentelemetry
    opentelemetry-api
    opentelemetry-sdk
    opentelemetry-semantic-conventions
    

    Query to get traces :

    traces
    | where message == "Hello Kamali"
    | project timestamp, message, customDimensions
    

    enter image description here

    Query to get metrics :

    customMetrics
    | project timestamp, name, value, customDimensions
    

    enter image description here

    Traces in Transaction Search :

    enter image description here