Azure Queue Trigger函数运行成功但Monitor标签页未捕获执行记录
Azure Queue Trigger函数运行成功但Monitor无成功记录的解决方法
问题描述
开发了Queue Trigger类型的Azure Function,队列有消息时函数可正常运行,但Azure门户的Monitor标签页无法捕获成功运行记录,成功次数始终为0。
函数代码
public class SendTestAlertFn { private readonly ILogger<SendTestAlert> log; private readonly AppSettings appSettings; private readonly ISendAlertService sendAlertService; public SendTestAlertFn(IOptions<AppSettings> appSettings, ILogger<SendTestAlert> log, ISendAlertService sendAlertService) { this.appSettings = appSettings.Value; this.log = log; this.sendAlertService = sendAlertService; } [FunctionName("TestFn")] public async Task Run([QueueTrigger("testqueue", Connection = "AzureWebJobsStorage")] string msgIn) { log.LogInformation($"started"); await sendAlertService.SendTestAlertAsync(); } }
Monitor标签页显示情况

问题原因及解决方法
1. 日志注入类型不匹配
代码中函数类为SendTestAlertFn,但注入的ILogger泛型参数是SendTestAlert,两者不一致会导致日志无法关联到当前函数,Monitor无法识别运行记录。
修正方法:将日志注入的类型改为与函数类一致:
// 构造函数参数和私有字段都改为ILogger<SendTestAlertFn> private readonly ILogger<SendTestAlertFn> log; public SendTestAlertFn(IOptions<AppSettings> appSettings, ILogger<SendTestAlertFn> log, ISendAlertService sendAlertService) { this.appSettings = appSettings.Value; this.log = log; this.sendAlertService = sendAlertService; }
2. 未正确配置Application Insights
Monitor依赖Application Insights采集运行日志,如果函数应用未关联Application Insights或配置错误,会导致记录缺失。
检查步骤:
- 进入Azure Function应用的配置页面,确认
APPINSIGHTS_INSTRUMENTATIONKEY已正确设置,且对应的Application Insights资源正常运行。 - 检查
host.json的日志配置,确保Application Insights采样和日志级别正确:
{ "logging": { "applicationInsights": { "samplingSettings": { "isEnabled": true, "excludedTypes": "Request" } }, "logLevel": { "default": "Information" } } }
3. 补充函数执行完成日志
在函数末尾添加执行完成的日志,帮助Application Insights更准确地捕获运行状态:
[FunctionName("TestFn")] public async Task Run([QueueTrigger("testqueue", Connection = "AzureWebJobsStorage")] string msgIn) { log.LogInformation($"函数开始执行,接收消息:{msgIn}"); await sendAlertService.SendTestAlertAsync(); log.LogInformation("函数执行完成"); }
完成以上修改后,重新部署函数,触发队列消息后即可在Monitor标签页看到成功运行记录。
内容的提问来源于stack exchange,提问作者CodingPanda
相关产品推荐
相关产品推荐

