Skip to content

Unable to emit metrics to application insights using pyhon opentelemetry #39904

Description

@sterankin

Based on this PR:
#34463

It appears it should be possible to emir custom metrics to a custom namespace from within an Azure function.

Currently I am using an Azure Apim to emit custom metrics like this:

        <emit-metric name="appid-info" namespace="opensource">
            <dimension name="api-name" value="@(context.Api.Name)" />
            <dimension name="app-id" value="@(context.Variables.GetValueOrDefault<string>("appid"))" />
            <dimension name="use-case" value="@(context.Variables.GetValueOrDefault<string>("inferred_raic_use_case_name"))" />
            <dimension name="user" value="@(context.Variables.GetValueOrDefault<string>("user"))" />
        </emit-metric>

However I am moving some functionality to a python function app which is being called from the APIM. I would like to continue using app insights custom metrics so they can be charted and graphed in app insights.

I have tried this:

requirements.txt:

azure-monitor-opentelemetry
azure-monitor-opentelemetry-exporter
opentelemetry-api
opentelemetry-sdk

Python:

from azure.monitor.opentelemetry.exporter import AzureMonitorLogExporter
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
from opentelemetry import metrics

def log_to_app_insights():
    """Log data to Azure Application Insights"""
    try:
        os.environ["APPLICATIONINSIGHTS_METRIC_NAMESPACE_OPT_IN"] = "true"
        exporter = AzureMonitorMetricExporter(
        connection_string=os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]
    )
        reader= PeriodicExportingMetricReader(exporter, export_interval_millis=5000)
        metrics.set_meter_provider(MeterProvider(metric_readers=[reader]))

        # metrics under this meter should show up under `testname` namespace in metrics explorer blade
        meter = metrics.get_meter("testname")
        counter= meter.create_counter("testcounter")
        counter.add(1)
        # Optionally, force export if you want on-demand export:
        reader.force_flush()

    except Exception as e:
        logging.error(f"Failed to log to Application Insights: {str(e)}")

The connection string is set correctly. I do not see the above metric in my logs. And why is there a periodic exporter set to 5000ms, I just want to export the logs at the end of the function call, preferably in an async manner.

The rest of my function executes fine (I am also logging to eventhub without issue) but i cannot get the app insights code to work - there are no errors in execution. Can anyone help spot the issue here?

Metadata

Metadata

Assignees

Labels

ClientThis issue points to a problem in the data-plane of the library.MonitorMonitor, Monitor Ingestion, Monitor QueryService AttentionWorkflow: This issue is responsible by Azure service team.customer-reportedIssues that are reported by GitHub users external to the Azure organization.issue-addressedWorkflow: The Azure SDK team believes it to be addressed and ready to close.needs-team-attentionWorkflow: This issue needs attention from Azure service team or SDK teamquestionThe issue doesn't require a change to the product in order to be resolved. Most issues start as that

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions