You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Azure Cache for Redis中的失败Hangfire任务配置Azure警报?

为Redis存储的Hangfire失败任务配置Azure警报方案

方法一:直接通过Azure Redis监控(局限性说明)

你尝试的Azure Redis自定义日志搜索方式无法直接检索Redis内的Hangfire任务数据——Azure Redis的日志搜索仅针对Redis本身的操作日志、性能指标(比如缓存命中率、连接数),不支持直接查询Redis键值对的具体内容。Hangfire的失败任务在Redis中以hangfire:failed有序集合(存储失败任务ID)和hangfire:job:{id}哈希结构(存储任务详情)存在,但Azure门户无法直接基于这些数据创建警报规则,所以这个路径走不通。

方法二:通过日志推送+Azure Monitor警报(推荐方案)

核心思路是:监听Hangfire任务失败事件,将失败信息以结构化日志形式推送到Azure Monitor,再基于日志内容创建警报规则。

步骤1:监听Hangfire失败事件并记录日志

在你的ASP.NET Core项目中,添加Hangfire的状态过滤器,捕获任务失败事件并输出结构化日志:

// 在Program.cs中注册过滤器(或Startup.cs,依项目结构而定)
var app = builder.Build();

// 获取Hangfire全局过滤器集合,添加失败任务日志过滤器
GlobalJobFilters.Filters.Add(app.Services.GetRequiredService<FailedJobLoggerFilter>());

// 自定义失败任务日志过滤器
public class FailedJobLoggerFilter : IElectStateFilter
{
    private readonly ILogger<FailedJobLoggerFilter> _logger;

    public FailedJobLoggerFilter(ILogger<FailedJobLoggerFilter> logger)
    {
        _logger = logger;
    }

    public void OnStateElection(ElectStateContext context)
    {
        // 捕获任务失败状态
        if (context.CandidateState is FailedState failedState)
        {
            _logger.LogError(
                "Hangfire任务失败 | 任务ID: {JobId} | 队列: {Queue} | 异常信息: {ExceptionMsg} | 已重试次数: {RetryCount}",
                context.BackgroundJob.Id,
                context.BackgroundJob.Queue,
                failedState.Exception.Message,
                context.BackgroundJob.RetryCount);
        }
    }
}

步骤2:将应用日志推送到Azure Monitor

配置ASP.NET Core日志框架,将日志发送到Azure Monitor:

  1. 在appsettings.json中添加Azure Monitor配置:
"Logging": {
  "LogLevel": {
    "Default": "Information",
    "Microsoft.AspNetCore": "Warning",
    "YourProjectNamespace.FailedJobLoggerFilter": "Error"
  },
  "AzureMonitor": {
    "ConnectionString": "你的Azure Monitor工作区连接字符串",
    "LogLevel": {
      "YourProjectNamespace.FailedJobLoggerFilter": "Error"
    }
  }
}
  1. 在Program.cs中启用Azure Monitor日志:
builder.Logging.AddAzureMonitor(options =>
{
    options.ConnectionString = builder.Configuration["Logging:AzureMonitor:ConnectionString"];
});

步骤3:创建Azure警报规则

  1. 进入Azure门户 -> 监控 -> 警报 -> 创建警报规则
  2. 选择资源:选择你的Azure Monitor日志工作区
  3. 添加条件:
    • 选择信号类型为自定义日志搜索
    • 输入Kusto查询语句(按需调整):
      AppTraces
      | where Message contains "Hangfire任务失败"
      | where Level == "Error"
      | summarize FailedCount = count() by bin(TimeGenerated, 5m)
      | where FailedCount > 0
      
    • 设置阈值:比如5分钟内FailedCount >=1时触发警报
  4. 配置动作组:添加邮件通知、短信、Webhook等你需要的警报触发动作
  5. 完成创建:设置警报名称、描述后保存规则

额外说明

如果需要更精细的监控(比如按队列、任务类型区分失败警报),可以在日志中添加更多维度的字段(比如任务所属业务模块、标签),然后在Kusto查询中添加过滤条件即可。

内容的提问来源于stack exchange,提问作者Hulkstance

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 02:34:56