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

如何使用Kusto检索Azure Function中Python logging()输出的日志消息

基于日志关键词检索的Kusto查询实现方案

核心逻辑是反向匹配日志内容:不再先固定单次运行的operation_Id、InvocationId再查日志,而是先直接对日志内容做关键词过滤,自动关联对应运行的全量信息,全程不需要硬编码运行标识。

基础版:直接检索匹配关键词的日志条目

适用于只需要快速定位包含指定关键词的日志内容的场景,直接复用原有日志字段提取逻辑,去掉硬编码ID的过滤条件即可:

union traces
| union exceptions
// 按需调整查询的时间范围,比如最近1天/7天/30天
| where timestamp > ago(7d)
// 替换成自己的函数应用名、函数名,避免跨应用的日志噪音
| where cloud_RoleName =~ '你的函数应用名称'
| where operation_Name =~ '你的函数名称'
// 替换成要检索的日志关键词,支持同时匹配多个词
| where has_any("报错关键词", "需要追踪的操作关键词")
// 保持原有代码的字段提取逻辑,直接输出可读的日志内容和级别
| project 
    timestamp, 
    operation_Id,
    InvocationId = customDimensions['InvocationId'],
    logLevel = customDimensions['LogLevel'],
    message = iff(message != '', message, iff(innermostMessage != '', innermostMessage, customDimensions.['prop__{OriginalFormat}']))
| order by timestamp desc

进阶版:按关键词定位日志后,自动拉取对应运行的全量上下文

适用于需要查看某条命中关键词的日志所属的那次函数运行的全部日志(也就是之前硬编码ID才能拿到的完整运行日志),通过Kusto的自关联逻辑自动匹配运行标识,完全不需要手动复制ID:

// 第一步:先找出所有包含目标关键词的日志,自动提取对应运行的ID,不需要手动复制
let matched_runs = 
    union traces
    | union exceptions
    | where timestamp > ago(7d)
    | where cloud_RoleName =~ '你的函数应用名称'
    | where operation_Name =~ '你的函数名称'
    | where has_any("你的目标关键词") // 替换成实际要查的内容
    | project operation_Id, InvocationId = customDimensions['InvocationId']
    // 去重,避免同一条日志被重复统计
    | distinct operation_Id, InvocationId;

// 第二步:基于提取到的运行ID,拉取这些运行产生的全部日志
union traces
| union exceptions
| where timestamp > ago(7d)
| where cloud_RoleName =~ '你的函数应用名称'
| where operation_Name =~ '你的函数名称'
// 自动匹配第一步找到的所有命中关键词的运行,无需手动填固定ID
| join kind=inner matched_runs on operation_Id, InvocationId
| project 
    timestamp,
    operation_Id,
    InvocationId = customDimensions['InvocationId'],
    logLevel = customDimensions['LogLevel'],
    message = iff(message != '', message, iff(innermostMessage != '', innermostMessage, customDimensions.['prop__{OriginalFormat}']))
| order by operation_Id asc, timestamp asc

实用注意事项

  • 关键词匹配可灵活切换:
    • has_any是推荐用法,支持同时匹配多个关键词,查询性能最优
    • 如果需要精确匹配某个完整短语,可以把has_any换成has
    • 如果需要匹配不规则的格式(比如带数字的动态内容),可以用matches regex写匹配规则
  • 如果需要同时查看每次运行的状态(成功/失败、返回码、耗时),可以在最后追加对requests表的关联查询,和之前写的元数据查询逻辑完全兼容
  • 日志量较大的生产环境,建议先把时间范围缩小到最近1-2天,再跑全量关键词查询,避免因为全表扫描导致查询超时

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.27 09:24:00