You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Azure Function指标发送至禁用本地身份验证的Application Insights

问题描述

我在处理Azure Function日志时遇到以下问题:希望将所有默认日志(包括指标等)重定向至已禁用Local authentication的Application Insights。当前架构如下:

  • 已禁用本地身份验证的Application Insights实例
  • 被授予该Application Insights“Monitoring Metrics Publisher”角色的Azure Function

我尝试使用微软文档中的两段代码:
一段可创建追踪器但无法转发指标:

from azure.identity import ManagedIdentityCredential

from opencensus.ext.azure.trace_exporter import AzureExporter
from opencensus.trace.samplers import ProbabilitySampler
from opencensus.trace.tracer import Tracer

credential = ManagedIdentityCredential()
tracer = Tracer(
    exporter=AzureExporter(credential=credential, connection_string="InstrumentationKey=<your-instrumentation-key>;IngestionEndpoint=<your-ingestion-endpoint>"),
    sampler=ProbabilitySampler(1.0)
)

另一段可添加日志处理程序,但未集成ManagedIdentityCredential:

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')
)

合并两段代码后函数可运行,但未发送任何指标。我的目标是恢复禁用Application Insights本地身份验证前能获取的所有Azure日志,请问该如何实现?


解决方案

1. 确认托管身份权限配置

确保Azure Function的托管身份(系统分配或用户分配)已被授予目标Application Insights的Monitoring Metrics Publisher和Log Analytics Contributor角色,确保身份拥有写入日志和指标的权限。

2. 完整集成日志、追踪与指标导出(含托管身份)

需要同时配置日志处理器、追踪器和指标导出器,全部使用ManagedIdentityCredential认证。以下是完整代码示例:

import logging
import azure.functions as func
from azure.identity import ManagedIdentityCredential
from opencensus.ext.azure.log_exporter import AzureLogHandler
from opencensus.ext.azure.trace_exporter import AzureExporter
from opencensus.ext.azure.metrics_exporter import AzureMetricsExporter
from opencensus.trace.samplers import ProbabilitySampler
from opencensus.trace.tracer import Tracer
from opencensus.stats import stats as stats_module
from opencensus.stats.aggregation import AggregationSum

# 初始化托管身份凭据
credential = ManagedIdentityCredential()

# Application Insights连接字符串:仅保留IngestionEndpoint,无需InstrumentationKey
AI_INGESTION_ENDPOINT = "https://<your-ai-ingestion-endpoint>/"
ai_connection_string = f"IngestionEndpoint={AI_INGESTION_ENDPOINT}"

# 配置日志处理器
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
log_handler = AzureLogHandler(
    connection_string=ai_connection_string,
    credential=credential
)
logger.addHandler(log_handler)

# 配置追踪器
tracer = Tracer(
    exporter=AzureExporter(
        connection_string=ai_connection_string,
        credential=credential
    ),
    sampler=ProbabilitySampler(1.0)
)

# 配置指标导出器
stats = stats_module.stats
view_manager = stats.view_manager
metrics_exporter = AzureMetricsExporter(
    connection_string=ai_connection_string,
    credential=credential
)
view_manager.register_exporter(metrics_exporter)

# 函数入口
def main(req: func.HttpRequest) -> func.HttpResponse:
    # 记录默认日志
    logger.info("HTTP请求已处理", extra={"custom_dimensions": {"path": req.path}})
    
    # 追踪代码执行
    with tracer.span(name="function-execution") as span:
        span.add_attribute("method", req.method)
        
    # 记录自定义指标(如需捕获内置指标,见下一步)
    from opencensus.stats.measure import MeasureInt
    from opencensus.stats.view import View
    measure_requests = MeasureInt("request_count", "请求总数", "requests")
    view_requests = View(
        "request_count_view",
        "请求统计",
        [],
        measure_requests,
        aggregation=AggregationSum()
    )
    view_manager.register_view(view_requests)
    
    mmap = stats_module.stats.measurement_map.MeasurementMap()
    mmap.measure_int_put(measure_requests, 1)
    mmap.record()
    
    return func.HttpResponse("处理完成", status_code=200)

3. 启用Azure Function内置日志与指标集成

要获取Function默认的运行指标(如调用次数、执行时长、错误率等),无需手动编码,直接在Function App配置中开启:

  • 进入Azure Function App的监控 > Application Insights
  • 关联目标Application Insights实例
  • 选择托管身份作为认证方式(匹配你使用的系统/用户分配身份)
  • 保存配置后,Function的内置日志和指标会自动通过托管身份发送到Application Insights

4. 验证数据传输

  • 执行几次Function请求后,到Application Insights的日志面板,查询traces、requests表查看日志
  • 在指标面板查看Function的内置指标(如Function Execution Count)是否正常显示

内容的提问来源于stack exchange,提问作者Chocamow

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 01:20:19