如何在ASP.NET中当运行状况检查返回“degraded”/“unhealthy”时发送电子邮件警报

wsxa1bj1  于 9个月前  发布在  .NET
关注(0)|答案(1)|浏览(80)

我已经在我的blazor应用程序中实现了健康检查。

Startup.cs

public void ConfigureServices(IServiceCollection services)
        {
            services.AddRazorPages();
            services.AddServerSideBlazor();
            services.AddHostedService<PeriodicExecutor>();
            services.AddHealthChecks()
            .AddCheck<EndpointHealth>("Endpoint",null) 
            .AddSqlServer(Configuration["sqlString"],
                healthQuery: "select 1",
                failureStatus: HealthStatus.Degraded,
                name: "SQL Server");
            services.AddHealthChecksUI(opt =>
            {
                opt.SetEvaluationTimeInSeconds(5); //time in seconds between check    
                opt.MaximumHistoryEntriesPerEndpoint(60); //maximum history of checks    
                opt.SetApiMaxActiveRequests(1); //api requests concurrency    
                opt.AddHealthCheckEndpoint("API", Configuration["healthEndpoint"]); //map health check api    
            }).AddInMemoryStorage();
        }
app.UseEndpoints(endpoints =>
            {
                endpoints.MapBlazorHub();
                endpoints.MapFallbackToPage("/_Host");
                endpoints.MapHealthChecks("/health", new HealthCheckOptions()
                {
                    Predicate = _ => true,
                    ResponseWriter = UIResponseWriter.
                    WriteHealthCheckUIResponse
                });
                endpoints.MapHealthChecksUI();
            });

为此,我使用了asp.net healthchecks包。我想知道的是,是否有一种方法可以在健康检查的状态更改为降级/不健康时发送电子邮件,而不必手动检查/health或/healthcheck-ui页面。

4nkexdtk

4nkexdtk1#

如何使用WebHook?更多详情请访问here
appsettings.json中的配置部分将向您定义的URL发送HTTP post:

"HealthChecksUI": {
    "HealthChecks": [
      {
        "Name": "Endpoint1",
        "Uri": "http://FQDN or HostName:Port/health"
      },
      /* Other endpoints go in here */
    ],
    "Webhooks": [
      {
        "Name": "Internal",
        "Uri": "/api/healthchecks/defaultnotify",
        "Payload": "{ \"message\": \"Webhook report for [[LIVENESS]]: [[FAILURE]] - Description: [[DESCRIPTIONS]]\"}",
        "RestoredPayload": "{ \"message\": \"[[LIVENESS]] is back to life\"}"
      }
    ],
    "EvaluationTimeInSeconds": 10,
    "MinimumSecondsBetweenFailureNotifications": 60
  }

在这种情况下,POST看起来像这样:

[HttpPost("DefaultNotify")]
    public async Task DefaultNotify(DefaultNotification defaultNotification)
    {
        _logger.LogInformation("Received default notification with message: {Message}", defaultNotification.Message);

        /* Other logic follows ... */
    }

发布的对象看起来像这样:

using System.Text.Json.Serialization;

public class DefaultNotification
{
    [JsonPropertyName("message")] public string? Message { get; set; }
}

相关问题