如何将Web App for Containers的容器stdout日志采集至Azure Application Insights?
可行的日志采集与指标提取方案
方案1:Azure Monitor日志采集+自定义指标生成
- 先在App Service门户的「日志」选项中,开启「应用日志(文件系统)」和「容器日志」,并配置将日志发送到Log Analytics工作区。容器的stdout日志会被自动收集到
AppServiceConsoleLogs或ContainerAppLogs表中。 - 用Log Analytics的Kusto查询语言从日志中提取指标,比如统计请求耗时、错误次数等,再将查询结果创建为自定义指标推送到Application Insights。
示例Kusto查询(假设日志包含request_duration字段):AppServiceConsoleLogs | where Message contains "request_duration" | parse Message with * "request_duration: " duration:int * | summarize avg_duration = avg(duration) by bin(TimeGenerated, 1m) - 将该查询保存为日志查询规则,设置把结果作为自定义指标发送到你的Application Insights实例。
方案2:Sidecar容器转发日志到Application Insights
- 在容器组中添加一个Sidecar容器,挂载Web App for Containers的日志目录(通常为
/var/log/containers)。 - 在Sidecar中用脚本或轻量工具读取日志文件,通过Application Insights的Ingestion API将日志内容发送到AI。
示例bash脚本(需替换你的检测密钥):tail -f /var/log/containers/your-app-container.log | while read line; do curl -X POST "https://dc.services.visualstudio.com/v2/track" \ -H "Content-Type: application/json" \ -H "Authorization: InstrumentationKey=YOUR_INSTRUMENTATION_KEY" \ -d '{ "name": "Microsoft.ApplicationInsights.Message", "time": "'$(date -u +"%Y-%m-%dT%H:%M:%SZ")'", "iKey": "YOUR_INSTRUMENTATION_KEY", "tags": {}, "data": { "baseType": "MessageData", "baseData": { "message": "'"$line"'", "severityLevel": "Information" } } }' done
方案3:Go应用输出结构化日志实现自动采集
- 手动构造符合Application Insights格式的JSON日志,直接输出到stdout,借助已启用的App Service AI集成自动解析采集。
示例Go代码:package main import ( "encoding/json" "fmt" "time" ) type AiLog struct { Message string `json:"message"` SeverityLevel string `json:"severityLevel"` Properties map[string]interface{} `json:"properties"` TimeGenerated string `json:"time"` } func main() { log := AiLog{ Message: "Request processed successfully", SeverityLevel: "Information", Properties: map[string]interface{}{ "request_id": "abc123", "duration": 120, }, TimeGenerated: time.Now().UTC().Format(time.RFC3339), } logJson, _ := json.Marshal(log) fmt.Println(string(logJson)) }
已尝试操作的补充说明
仅添加检测密钥和启用门户集成,无法自动采集非结构化stdout日志。需确保日志为结构化JSON格式,或通过Log Analytics中转处理,可在App Service的Application Insights「日志」标签页检查是否有日志被正常采集。
内容的提问来源于stack exchange,提问作者MartyMe
相关产品推荐
相关产品推荐

