如何在Application Insights中基于customMeasurements生成文件类型统计饼图?
问题场景
处理作业时通过TrackEvent记录文件处理事件,每种文件类型在customMeasurements中以键值对形式存储(符合条件则值为1,否则为0),代码示例:
tc.TrackEvent("File processed", metrics: new Dictionary<string, double>{ { "HTML", FileType == 0 ? 1 : 0 }, { "Excel", FileType == 1 ? 1 : 0}, { "CSV", FileType == 2 ? 1 : 0}, { "XML" , FileType == 3 ? 1 : 0}, ...
当前使用的Log Query生成横向汇总表,无法直接用于创建饼图:
customEvents | project csv=todouble(customMeasurements['CSV']), excel = todouble(customMeasurements['Excel']), html = todouble(customMeasurements['HTML']), xml = todouble(customMeasurements['XML']) | summarize sum(csv), sum(excel), sum(html), sum(xml)
生成结果:
| sum_csv | sum_excel | sum_html | sum_xml |
|---|---|---|---|
| 3 | 230 | 100 | 45 |
需要转换为纵向统计格式:
| File type | Count |
|---|---|
| HTML | 100 |
| XML | 45 |
| Excel | 230 |
| CSV | 3 |
解决方案
提供两种Log Query实现方式:
方法1:动态展开自定义度量(推荐,无需硬编码类型)
该方法自动遍历customMeasurements中的所有键值对,过滤出值为1的条目后汇总,适合文件类型可能新增的场景:
customEvents | where name == "File processed" | mv-apply kv = customMeasurements on ( where tolong(kv.Value) == 1 | project FileType = kv.Key, Count = tolong(kv.Value) ) | summarize Count = sum(Count) by FileType
方法2:固定列转行(适合类型固定的场景)
如果文件类型不会变动,可直接将横向汇总结果转换为纵向格式:
customEvents | project csv=todouble(customMeasurements['CSV']), excel=todouble(customMeasurements['Excel']), html=todouble(customMeasurements['HTML']), xml=todouble(customMeasurements['XML']) | summarize sum_csv=sum(csv), sum_excel=sum(excel), sum_html=sum(html), sum_xml=sum(xml) | union (print FileType="CSV", Count=sum_csv), (print FileType="Excel", Count=sum_excel), (print FileType="HTML", Count=sum_html), (print FileType="XML", Count=sum_xml) | where Count > 0 // 可选,过滤无数据的类型
执行任意一种查询后,即可得到符合要求的纵向统计表格,直接用于创建饼图。
内容的提问来源于stack exchange,提问作者Menelaos Vergis
相关产品推荐
相关产品推荐

