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

如何为Python Azure Function配置App Insights跟踪Blob存储依赖?

实现Blob存储操作的App Insights依赖追踪步骤

针对你的需求,需要完成以下几项关键调整:

1. 修正host.json的采样配置

当前samplingSettings里的excludedTypes包含了Dependency,这会直接阻止依赖追踪数据被发送到App Insights。修改该配置,移除Dependency:

{
  "version": "2.0",
  "logging": {
    "applicationInsights": {
      "enableDependencyTracking": true,
      "dependencyTrackingOptions": {
        "enableSqlCommandTextInstrumentation": true
      },
      "samplingSettings": {
        "isEnabled": true,
        "excludedTypes": "Request;Exception"
      }
    }
  },
  "extensionBundle": {
    "id": "Microsoft.Azure.Functions.ExtensionBundle",
    "version": "[2.*, 3.0.0)"
  }
}

2. 添加必要的Python依赖包

在你的Function项目的requirements.txt中添加OpenCensus相关包,用于支持Python SDK与App Insights的追踪集成:

azure-functions>=1.14.0
azure-storage-blob>=12.19.0
azure-identity>=1.15.0
opencensus-ext-azure>=1.1.9
opencensus-ext-azure-functions>=1.1.0

3. 配置App Insights连接信息

在Azure门户的Function应用配置中,添加环境变量APPLICATIONINSIGHTS_CONNECTION_STRING,值为你的App Insights实例对应的连接字符串(可从App Insights门户的“概述”页面获取)。

4. 初始化追踪(可选但推荐)

在函数代码开头添加追踪初始化逻辑,确保OpenCensus能正确捕获Blob操作的依赖:

import os
import azure.functions as func
from azure.storage.blob import BlobServiceClient
from azure.identity import DefaultAzureCredential
# 新增追踪相关导入
from opencensus.ext.azure.functions import OpenCensusExtension
from opencensus.trace.samplers import ProbabilitySampler
from opencensus.ext.azure.trace_exporter import AzureExporter

# 初始化OpenCensus扩展
OpenCensusExtension.configure()
tracer = Tracer(
    sampler=ProbabilitySampler(1.0),
    exporter=AzureExporter(connection_string=os.getenv("APPLICATIONINSIGHTS_CONNECTION_STRING"))
)

def main(req: func.HttpRequest) -> func.HttpResponse:    
    default_credential = DefaultAzureCredential(exclude_shared_token_cache_credential=True)
    blob_storage_uri = "https://mystorage.blob.core.windows.net"

    # 用trace包裹Blob操作代码,确保依赖被捕获
    with tracer.span(name="Blob-Download-Operation"):
        blob_service_client = BlobServiceClient(blob_storage_uri, credential=default_credential)
        container_client = blob_service_client.get_container_client("my-container")
        blob_client = container_client.get_blob_client("files/stefan/my_file.json")
        blob_data = blob_client.download_blob().readall()
    
    return func.HttpResponse(blob_data, status_code=200)

5. 验证结果

部署修改后的代码和配置,触发函数调用后,前往App Insights门户的“依赖项”面板,即可查看Blob存储的调用记录,包括操作类型、目标地址、响应时间等信息。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 18:34:57