mcpField
D
dotnet-health-checks

dotnet-health-checks

github.com/ronnythedevクラウド・DevOps7762 回インストール15 週間前に更新
リポジトリ

dotnet-health-checks について

.NET アプリケーションの依存関係や独自ロジックを対象に、ヘルスチェックを設定するスキルです。ライブネスとレディネスのエンドポイントに加え、データベースや外部サービスなどの例を扱います。

主な機能

  1. 01ライブネスとレディネスのチェック
  2. 02PostgreSQL 接続チェック
  3. 03HTTP エンドポイントのチェック
  4. 04Redis と RabbitMQ のチェック
  5. 05独自のアプリケーションヘルスチェック

活用シーン

  1. 01トラフィック振り分け用のアプリ状態確認
  2. 02PostgreSQL 接続の監視
  3. 03外部 API の稼働確認
  4. 04独自のデータベース移行チェックの追加

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/ronnythedev/dotnet-clean-architecture-skills --skill dotnet-health-checks

インストール後、Claude Code で/dotnet-health-checksを入力して読み込まれたか確認します。

詳細

ヘルスチェックの設定

概要

ヘルスチェックでは、アプリケーションの依存関係を監視します。

  • ライブネス - アプリケーションは実行中ですか?
  • レディネス - アプリケーションはトラフィックを処理できる状態ですか?
  • データベースチェック - PostgreSQL への接続
  • 外部サービスチェック - API、キャッシュ、キュー
  • カスタムチェック - ビジネスロジックの検証

クイックリファレンス

チェックの種類目的
AddNpgSqlPostgreSQL データベース
AddUrlGroup外部 HTTP エンドポイント
AddRedisRedis キャッシュ
AddRabbitMQRabbitMQ メッセージブローカー
カスタムアプリケーション固有のチェック

テンプレート:ヘルスチェックの登録

// src/{name}.infrastructure/HealthChecks/HealthCheckExtensions.cs
using Microsoft.Extensions.Diagnostics.HealthChecks;

namespace {name}.infrastructure.healthchecks;

public static class HealthCheckExtensions
{
    public static IServiceCollection AddHealthChecks(
        this IServiceCollection services,
        IConfiguration configuration)
    {
        services.AddHealthChecks()
            // ═══════════════════════════════════════════════════════════════
            // DATABASE
            // ═══════════════════════════════════════════════════════════════
            .AddNpgSql(
                configuration.GetConnectionString("Database")!,
                name: "postgresql",
                failureStatus: HealthStatus.Unhealthy,
                tags: new[] { "db", "sql", "postgresql", "ready" })

            // ═══════════════════════════════════════════════════════════════
            // EXTERNAL SERVICES
            // ═══════════════════════════════════════════════════════════════
            .AddUrlGroup(
                new Uri(configuration["AuthService:BaseUrl"]!),
                name: "auth-service",
                failureStatus: HealthStatus.Degraded,
                tags: new[] { "external", "auth", "ready" })

            // ═══════════════════════════════════════════════════════════════
            // REDIS (if used)
            // ═══════════════════════════════════════════════════════════════
            // .AddRedis(
            //     configuration.GetConnectionString("Redis")!,
            //     name: "redis",
            //     tags: new[] { "cache", "redis", "ready" })

            // ═══════════════════════════════════════════════════════════════
            // CUSTOM CHECKS
            // ═══════════════════════════════════════════════════════════════
            .AddCheck<DatabaseMigrationHealthCheck>(
                "database-migrations",
                tags: new[] { "db", "migrations", "ready" });

        return services;
    }
}

テンプレート:カスタムヘルスチェック

// src/{name}.infrastructure/HealthChecks/DatabaseMigrationHealthCheck.cs
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Diagnostics.HealthChecks;

namespace {name}.infrastructure.healthchecks;

internal sealed class DatabaseMigrationHealthCheck : IHealthCheck
{
    private readonly ApplicationDbContext _dbContext;

    public DatabaseMigrationHealthCheck(ApplicationDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    public async Task<HealthCheckResult> CheckHealthAsync(
        HealthCheckContext context,
        CancellationToken cancellationToken = default)
    {
        try
        {
            var pendingMigrations = await _dbContext.Database
                .GetPendingMigrationsAsync(cancellationToken);

            var pending = pendingMigrations.ToList();

            if (pending.Any())
            {
                return HealthCheckResult.Degraded(
                    $"Pending migrations: {string.Join(", ", pending)}",
                    data: new Dictionary<string, object>
                    {
                        { "pending_count", pending.Count },
                        { "migrations", pending }
                    });
            }

            return HealthCheckResult.Healthy("All migrations applied");
        }
        catch (Exception ex)
        {
            return HealthCheckResult.Unhealthy(
                "Failed to check migrations",
                exception: ex);
        }
    }
}

テンプレート:Program.cs の設定

// src/{name}.api/Program.cs
using HealthChecks.UI.Client;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;

var app = builder.Build();

// ═══════════════════════════════════════════════════════════════
// LIVENESS: Is the app running?
// ═══════════════════════════════════════════════════════════════
app.MapHealthChecks("/health/live", new HealthCheckOptions
{
    Predicate = _ => false,  // No checks, just confirms app is running
    ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
});

// ═══════════════════════════════════════════════════════════════
// READINESS: Is the app ready to serve traffic?
// ═══════════════════════════════════════════════════════════════
app.MapHealthChecks("/health/ready", new HealthCheckOptions
{
    Predicate = check => check.Tags.Contains("ready"),
    ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
});

// ═══════════════════════════════════════════════════════════════
// FULL: All health checks
// ═══════════════════════════════════════════════════════════════
app.MapHealthChecks("/health", new HealthCheckOptions
{
    ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
});

Kubernetes の設定

# deployment.yaml
apiVersion: apps/v1
kind: Deployment
spec:
  template:
    spec:
      containers:
        - name: api
          livenessProbe:
            httpGet:
              path: /health/live
              port: 8080
            initialDelaySeconds: 10
            periodSeconds: 30
          readinessProbe:
            httpGet:
              path: /health/ready
              port: 8080
            initialDelaySeconds: 5
            periodSeconds: 10

関連スキル

  • dotnet-clean-architecture - インフラストラクチャ層のセットアップ
  • dotnet-jwt-authentication - 認証サービスのヘルスチェック

コメント