Friday, February 21, 2025

How does azure function app with python code updates azure app insights

Azure Application Insights helps monitor logs, exceptions, performance metrics, and telemetry data for Azure Functions. To integrate Python-based Azure Functions with Application Insights, follow these steps:
--------

1. Prerequisites

Azure Function App (Python)

Azure Application Insights Resource

Instrumentation Key or Connection String

-------

2. Enable Application Insights for Azure Function App

Option 1: Enable via Azure CLI

az monitor app-insights component create --app <APP_INSIGHTS_NAME> --resource-group <RESOURCE_GROUP> --location eastus
az functionapp config appsettings set --name <FUNCTION_APP_NAME> --resource-group <RESOURCE_GROUP> \
    --settings "APPINSIGHTS_INSTRUMENTATIONKEY=<YOUR_INSTRUMENTATION_KEY>"

OR use the Connection String (recommended for newer versions):

az functionapp config appsettings set --name <FUNCTION_APP_NAME> --resource-group <RESOURCE_GROUP> \
    --settings "APPLICATIONINSIGHTS_CONNECTION_STRING=<YOUR_CONNECTION_STRING>"

------

3. Install & Configure Application Insights in Python

Install the Azure Monitor OpenTelemetry SDK:

pip install opentelemetry-sdk opentelemetry-exporter-azure-monitor

Modify your __init__.py to include Application Insights logging:

import logging
import azure.functions as func
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
from opentelemetry.exporter.azuremonitor import AzureMonitorSpanExporter

# Setup Application Insights Telemetry
instrumentation_key = "<YOUR_INSTRUMENTATION_KEY>"  # Or fetch from env variable
tracer = TracerProvider()
tracer.add_span_processor(SimpleSpanProcessor(AzureMonitorSpanExporter.from_connection_string(instrumentation_key)))

def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info("Processing request...")
    return func.HttpResponse("Hello from Azure Function with App Insights!")

---

4. Verify Logs in Application Insights

1. Go to Azure Portal → Application Insights


2. Navigate to Logs → Run the following Kusto Query:

traces
| where timestamp > ago(10m)
| order by timestamp desc


3. Check if your function's logs appear.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...