问题描述
是否可以在位置队列之外创建警报?我有一个 blob 触发器函数,但是当它失败 x
次时,它会将此消息抛出到毒物队列中。我想要做的是当毒药队列的计数为 x
时创建警报。
- 我可以使用 sidecart 方法来做到这一点,在那里我有一个独立的服务来监控中毒队列
- 看到这种方法https://stackoverflow.com/a/46334184/1134076
- 希望使用
blobproperties
覆盖来存储一些Metadata
以便我可以跟踪失败,但似乎没有办法做到这一点?我正在考虑在最后一次尝试中跟踪一个事件以声明moving message to poison queue
有没有更好的方法来做到这一点?
[FunctionName("MyFunction")]
public async Task Run(
[BlobTrigger("input-queue",Connection = "ConnectionString")] Stream blobContent,string name,System.Uri uri,IDictionary<string,string> MetaData,BlobProperties properties,ILogger log)
编辑 注意到函数的这个重载:
[FunctionName("MyFunction")]
public async Task Run(
[BlobTrigger("input-queue",Connection = "ConnectionString")] ICloudBlob blobContent,ILogger log)
{
if (!blobContent.Metadata.ContainsKey("mycount"))
{
blobContent.Metadata["mycount"] = "1";
await blobContent.SetMetadataAsync();
}
else
{
var value = int.Parse(blobContent.Metadata["mycount"]);
value++;
blobContent.Metadata["mycount"] = value.ToString();
await blobContent.SetMetadataAsync();
}
throw new Exception(("Testing Function"));
}
似乎有点矫枉过正,但我可以在这里跟踪失败计数并编写逻辑来跟踪自定义事件。
解决方法
我更喜欢的方法是使用 Azure 函数定期计算中毒队列中的项目数,并将其作为 Application Insights 指标发布。然后您可以从那里设置查询/仪表板/警报。
此方法的基本概述是 here。请注意,现代 Azure Functions 允许您使用 DI 和其他优点。
每 5 分钟定时器触发的函数示例,该函数获取有害队列计数并将其作为指标发布:
[FunctionName(nameof(TrackQueueMetrics))]
public async Task TrackQueueMetrics([TimerTrigger("0 */5 * * * *")] TimerInfo message)
{
var queues = await _queueService.GetAllQueuesAsync();
var poisonQueues = queues.Where(x => x.EndsWith("-poison",StringComparison.InvariantCultureIgnoreCase)).ToList();
var poisonQueueCounts = await Task.WhenAll(poisonQueues.Select(_queueService.GetApproximateMessagesCountAsync));
var fatalErrors = poisonQueueCounts.Sum();
_metrics.TrackFatalErrorsCount(fatalErrors);
}
GetAllQueuesAsync()
本质上是:
public async Task<IReadOnlyList<string>> GetAllQueuesAsync()
{
var result = new List<string>();
await foreach (var item in _queueServiceClient.GetQueuesAsync())
result.Add(item.Name);
return result;
}
GetApproximateMessagesCount()
本质上是:
public async Task<int> GetApproximateMessagesCountAsync(string queueName)
{
var properties = await _queueServiceClient.GetQueueClient(queueName).GetPropertiesAsync();
return properties.Value.ApproximateMessagesCount;
}
和 TrackFatalErrorsCount
本质上是:
public sealed class SingletonMetricsClient
{
private readonly Metric _fatalErrorsCountMetric;
public SingletonMetricsClient(TelemetryConfiguration telemetryConfiguration)
{
var client = new TelemetryClient(telemetryConfiguration);
_fatalErrorsCountMetric = client.GetMetric("FatalErrors");
}
public void TrackFatalErrorsCount(int count) => _fatalErrorsCountMetric.TrackValue(count);
}
将其作为指标后,您就可以查询它、为 Azure 仪表板构建图表和/或设置 Application Insights 警报。