Python如何不依赖弃用库向Application Insights customEvents写入数据以使用Usage功能
解决方案:在Python中向Application Insights写入customEvents以支持Usage模块
要满足需求(不用已弃用库,让Application Insights的Users、Events、Sessions功能正常工作),核心是向customEvents表写入包含用户、会话标识的自定义事件,以下是两种可行方案:
方案1:使用Azure Monitor Ingestion SDK直接发送自定义事件
这是当前官方推荐的方式,无需依赖已弃用的库,可直接构造符合customEvents格式的事件并发送到Application Insights。
步骤:
- 安装依赖包:
pip install azure-monitor-ingestion azure-identity
- 编写代码发送自定义事件:
from azure.identity import DefaultAzureCredential from azure.monitor.ingestion import LogsIngestionClient from datetime import datetime import uuid # 配置参数 DATA_COLLECTION_ENDPOINT = "<你的数据收集端点URL>" DATA_RULE_ID = "<你的数据收集规则ID>" STREAM_NAME = "<自定义事件对应的流名称,通常为CustomEvents>" # 初始化客户端 client = LogsIngestionClient(endpoint=DATA_COLLECTION_ENDPOINT, credential=DefaultAzureCredential()) # 构造自定义事件(包含Usage模块所需的关键字段) custom_event = [ { "name": "UserAction", "time": datetime.utcnow().isoformat() + "Z", "iKey": "<你的Application Insights Instrumentation Key>", "tags": { "ai.user.id": "user_123", # 用户标识,用于Users统计 "ai.session.id": str(uuid.uuid4()) # 会话标识,用于Sessions统计 }, "properties": { "action": "click_button", "page": "homepage" } } ] # 发送事件 client.upload(rule_id=DATA_RULE_ID, stream_name=STREAM_NAME, logs=custom_event)
说明:
ai.user.id和ai.session.id是Application Insights识别用户、会话的核心字段,必须正确设置;- 数据收集端点和规则ID需要在Azure门户中创建并配置,确保流指向Application Insights的
customEvents表。
方案2:结合OpenCensus与Azure REST API补充自定义事件
如果你需要继续使用OpenCensus处理追踪,可额外通过Azure Application Insights的REST API发送自定义事件,避免依赖弃用库。
代码示例:
import requests import uuid from datetime import datetime import json # 配置参数 INSTRUMENTATION_KEY = "<你的Application Insights Instrumentation Key>" API_ENDPOINT = f"https://dc.services.visualstudio.com/v2/track" # 构造自定义事件数据 event_data = { "name": "Microsoft.ApplicationInsights.Event", "time": datetime.utcnow().isoformat() + "Z", "iKey": INSTRUMENTATION_KEY, "tags": { "ai.user.id": "user_456", "ai.session.id": str(uuid.uuid4()) }, "data": { "baseType": "EventData", "baseData": { "ver": 2, "name": "PageView", "properties": { "page_url": "/product/detail" } } } } # 发送请求 headers = {"Content-Type": "application/json"} response = requests.post(API_ENDPOINT, data=json.dumps([event_data]), headers=headers) response.raise_for_status()
说明:
- 该方式直接调用Application Insights的追踪API,无需额外SDK;
- 同样需要确保
ai.user.id和ai.session.id字段正确设置,Usage模块会自动基于这些字段统计用户、会话数据。
关键注意事项
- 无论哪种方案,必须正确设置用户和会话标识,否则Usage模块无法生成准确的Users、Sessions统计;
- 避免使用已弃用的
applicationinsightsSDK,优先选择Azure Monitor Ingestion SDK或官方REST API; - 确保Azure资源的权限配置正确,比如使用
DefaultAzureCredential时,需要赋予代码运行环境对应的日志写入权限。
内容的提问来源于stack exchange,提问作者Dmitry Sazhnev
相关产品推荐
相关产品推荐

