Skip to content
ftamminga edited this page Apr 6, 2018 · 4 revisions

From the original Java library:

Metrics also provides you with a consistent, unified way of performing application health checks. A health check is basically a small self-test which your application performs to verify that a specific component or responsibility is performing correctly.

Example

public static void RegisterHealthChecks()
{
    HealthChecks.RegisterHealthCheck("DatabaseConnected", () =>
    {
        CheckDbIsConnected();
        return "Database Connection OK";
    });

    HealthChecks.RegisterHealthCheck("DiskSpace", () =>
    {
        int freeDiskSpace = GetFreeDiskSpace();

        if (freeDiskSpace <= 512)
        {
            return HealthCheckResult.Unhealthy("Not enough disk space: {0}", freeDiskSpace);
        }
        else
        {
            return HealthCheckResult.Healthy("Disk space ok: {0}", freeDiskSpace);
        }
    });

    HealthChecks.RegisterHealthCheck("SampleOperation", () => SampleOperation());
}

Or you can inherit HealthCheck class and write your own logic:

public class DatabaseHealthCheck : HealthCheck
{
    private readonly IDatabase database;
    public DatabaseHealthCheck(IDatabase database)
        : base("DatabaseCheck")
    {
        this.database = database;
        HealthChecks.RegisterHealthCheck(this);
    }

    protected override HealthCheckResult Check()
    {
        // exceptions will be caught and 
        // the result will be unhealthy
        this.database.Ping();
        return HealthCheckResult.Healthy();
    }
}

The status of the registered health checks can be queried by using:

    HealthChecks.GetStatus()