Azure Function中Application Insights日志不遵循host.json配置
问题描述
已为Azure Function App启用Application Insights,日志可正常记录,但所有日志级别的消息均被写入Application Insights的traces表中。按官方文档配置host.json的logLevel节点(默认设为None,Function设为Information及以上级别等),甚至测试了仅保留default: "None"的配置,均无法限制Application Insights中的日志范围;尝试将logLevel定义在applicationInsights子节也无效(且不符合官方参考文档的有效配置要求)。修改logLevel可正常控制本地运行时的控制台日志级别,但对Application Insights中记录的内容无影响,目前因日志数据量过大导致成本过高,无法正常使用Application Insights。
用户提供的完整host.json配置如下:
{ "version": "2.0", "logging": { "logLevel": { "default": "None", "Host.Results": "None", "Function": "Information", "Host.Aggregator": "Trace" }, "applicationInsights": { "samplingSettings": { "isEnabled": true, "excludedTypes": "Dependency;Request;PageView", "maxTelemetryItemsPerSecond" : 20, "httpAutoCollectionOptions": { "enableHttpTriggerExtendedInfoCollection": true, "enableW3CDistributedTracing": false, "enableResponseHeaderInjection": false } } } }, "extensionBundle": { "id": "Microsoft.Azure.Functions.ExtensionBundle", "version": "[3.*, 4.0.0)" }, "functionTimeout": "02:00:00", "extensions": { "queues": { "maxPollingInterval": "00:00:01", "visibilityTimeout" : "00:00:15", "batchSize": 1, "newBatchThreshold": 2, "maxDequeueCount": 2 } } }
解决方案
1. 排查Function App门户端的配置覆盖
- 进入Function App门户,依次打开「监控」→「日志」→「配置」,检查是否存在额外的日志筛选规则,确保没有强制记录所有级别的设置。
- 查看「配置」→「应用程序设置」,确认是否存在类似
AzureFunctionsJobHost__logging__applicationInsights__logLevel的环境变量,这类变量会直接覆盖host.json中的配置,若存在则删除或调整为符合需求的级别。
2. 确认日志调用方式合规
- 确保函数代码中仅使用官方提供的
ILogger接口记录日志,避免直接调用Application Insights的TelemetryClient.TrackTrace方法——后者会绕过host.json的日志级别限制,直接将日志写入traces表。
3. 利用Application Insights预处理规则过滤日志
- 进入Application Insights门户,打开「数据」→「预处理」,创建新的预处理规则:
- 规则类型选择「筛选痕迹」
- 设置条件为
trace.severityLevel小于Information(即过滤Debug、Verbose级别的日志) - 动作选择「丢弃痕迹」
- 该规则会在日志数据进入Application Insights前直接过滤不符合要求的条目,从根源减少日志量。
4. 验证host.json配置并重启Function App
- 确认
logLevel节点直接位于logging根节点下(而非嵌套在applicationInsights内),且命名空间拼写正确(如Function、Host.Results)。 - 修改
host.json后,务必重启Function App,确保配置生效。
5. 调整采样设置辅助限流
- 当前
samplingSettings中的maxTelemetryItemsPerSecond设为20,仅用于控制每秒发送的日志数量,无法过滤级别。若日志量仍过大,可结合级别过滤进一步降低采样阈值,或扩大excludedTypes的范围(需谨慎操作,避免丢失关键日志)。
内容的提问来源于stack exchange,提问作者Gabriel Ruoff
相关产品推荐
相关产品推荐

