如何自动将Log Analytics查询告警转换为Application Insights查询?
解决方案:Log Analytics Kusto 查询转 Application Insights 自动化方案
核心思路:预定义映射+查询解析替换
Log Analytics 与 Application Insights 的表、字段差异存在固定规律,通过预定义映射规则结合查询文本的解析替换,即可实现自动化转换,以下是可落地的集成方案:
1. 先整理映射规则字典
先梳理常见的表和字段对应关系,用结构化格式存储(比如 JSON),方便后续调用:
{ "tableMappings": { "Heartbeat": "availabilityResults", "Event": "customEvents", "Perf": "performanceCounters", "Syslog": "customLogs" }, "fieldMappings": { "TimeGenerated": "timestamp", "Computer": "cloud_RoleInstance", "EventID": "customDimensions.EventID", "ObjectName": "category" } }
2. 可集成的 Python 转换脚本
编写轻量脚本实现查询替换,支持复杂字段/表名的精准匹配:
import re def convert_la_to_ai_query(la_query, table_maps, field_maps): # 替换表名(匹配独立单词,避免误替换) for la_table, ai_table in table_maps.items(): la_query = re.sub(rf'\b{la_table}\b', ai_table, la_query) # 替换字段名 for la_field, ai_field in field_maps.items(): la_query = re.sub(rf'\b{la_field}\b', ai_field, la_query) return la_query # 示例调用 mapping_config = { "tableMappings": {"Heartbeat": "availabilityResults"}, "fieldMappings": {"TimeGenerated": "timestamp", "Computer": "cloud_RoleInstance"} } la_sample_query = """Heartbeat | where TimeGenerated > ago(5m) | summarize count() by Computer""" ai_converted_query = convert_la_to_ai_query(la_sample_query, mapping_config["tableMappings"], mapping_config["fieldMappings"]) print(ai_converted_query)
执行后输出目标查询:
availabilityResults | where timestamp > ago(5m) | summarize count() by cloud_RoleInstance
3. 集成到 CI/CD 管道
- 将脚本作为 CI/CD 步骤(比如 Azure DevOps Pipeline、GitHub Actions),读取存储在配置中心/密钥库的映射规则和原始 Log Analytics 查询
- 转换完成后,调用 Azure CLI 或 REST API 自动创建/更新 Application Insights 告警规则:
- Azure CLI 示例:
az monitor alert create --resource-group <rg-name> --name <alert-name> --condition "count availabilityResults | where timestamp > ago(5m) | summarize count() by cloud_RoleInstance" --action <action-group-id>
- Azure CLI 示例:
4. 基于 Azure Functions/Logic Apps 的无代码集成
- Azure Functions:将转换脚本部署为 HTTP 触发的函数,接收原始查询和映射参数,返回转换后的结果,后续对接 Azure Monitor API 完成告警创建
- Logic Apps:通过 HTTP 触发器接收查询,调用上述 Azure Functions 做转换,再使用「Azure Monitor - 创建告警规则」内置动作完成配置,无需编写复杂代码
注意事项
- 对于嵌套查询、自定义函数等复杂 Kusto 语句,需扩展脚本逻辑,可借助
Microsoft.Azure.Kusto.LanguageSDK 做语法解析后再替换节点 - 需定期维护映射字典,适配 Azure 平台的表/字段命名更新
内容的提问来源于stack exchange,提问作者Vowneee
相关产品推荐
相关产品推荐

