ans-group/laravel-health-check

用于检查Laravel/Lumen应用程序健康状况的包。

v2.0.1 2024-09-09 15:52 UTC

README

UKFast Logo

Tests

健康检查包

此包的目的是在/health上暴露一个健康检查端点,当访问该端点时,返回项目依赖的所有服务和依赖项的状态,以及系统的整体健康状况。这在开发和生产环境中都很有用,可以用于调试有问题的应用程序的问题。

此包还添加了一个/ping端点。只需访问/ping,即可收到pong响应。

安装

要安装此包

运行composer require ans-group/laravel-health-check以将包添加到依赖项中。

这将自动将包安装到您的vendor文件夹中。

Laravel

在Laravel应用程序中,服务提供者应自动注册,但您可以在您的config/app.php文件中手动注册它

'providers' => [
    // ...
    UKFast\HealthCheck\HealthCheckServiceProvider::class,
];  

Lumen

要使包在Lumen中工作,您需要注册服务提供者。将以下内容添加到您的bootstrap/app.php文件中

$app->register(\UKFast\HealthCheck\HealthCheckServiceProvider::class);

您可以通过访问/health端点来测试包是否正确工作。

配置

Laravel

外观

我们通过包提供了一个HealthCheck外观。如果您想从代码中访问检查结果或正在运行的检查数量,可以使用passesfailsall方法。

if (HealthCheck::passes('env')) {
    // check passed
}

if (HealthCheck::fails('http')) {
    // check failed
}

$numberOfChecks = HealthCheck::all()->count();

如果提供的某个检查无法从服务容器中解析出来,我们将抛出一个带有缺失检查名称的CheckNotFoundException

配置

如果您想修改配置文件(例如,配置EnvHealthCheck),可以使用以下命令发布它

php artisan vendor:publish --provider="UKFast\HealthCheck\HealthCheckServiceProvider" --tag="config"
控制台命令

检查全部:php artisan health-check:status

只检查特定检查:php artisan health-check:status --only=log,cache

排除特定检查:php artisan health-check:status --except=cache

中间件

您可以为访问/health端点的请求注册自定义中间件。您可以将以下内容添加到上面命令创建的config/healthcheck.php配置文件中的中间件数组中,如下所示

/**
 * A list of middleware to run on the health-check route
 * It's recommended that you have a middleware that only
 * allows admin consumers to see the endpoint.
 *
 * See UKFast\HealthCheck\Middleware\BasicAuth for a one-size-fits all
 * solution
 */
'middleware' => [
    App\Http\Middleware\CustomMiddleware::class
],

现在您的CustomMiddleware中间件将在每个请求到/health端点时运行。

Lumen

外观

我们通过包提供了一个HealthCheck外观。如果您想从代码中访问检查结果或正在运行的检查数量,可以使用passesfailsall方法。

if (HealthCheck::passes('env')) {
    // check passed
}

if (HealthCheck::fails('http')) {
    // check failed
}

$numberOfChecks = HealthCheck::all()->count();

如果提供的某个检查无法从服务容器中解析出来,我们将抛出一个带有缺失检查名称的CheckNotFoundException

配置

如果您想修改配置文件(例如,配置EnvHealthCheck

手动将包配置文件(如下所示)复制到config\healthcheck.php(如果不存在,您可能需要创建配置目录)。

<?php

return [
    /**
     * Base path for the health check endpoints, by default will use /
     */
    'base-path' => '',

    /**
     * List of health checks to run when determining the health
     * of the service
     */
    'checks' => [
        UKFast\HealthCheck\Checks\LogHealthCheck::class,
        UKFast\HealthCheck\Checks\DatabaseHealthCheck::class,
        UKFast\HealthCheck\Checks\EnvHealthCheck::class
    ],

    /**
     * A list of middleware to run on the health-check route
     * It's recommended that you have a middleware that only
     * allows admin consumers to see the endpoint.
     * 
     * See UKFast\HealthCheck\BasicAuth for a one-size-fits all
     * solution
     */
    'middleware' => [],

    /**
     * Used by the basic auth middleware
     */
    'auth' => [
        'user' => env('HEALTH_CHECK_USER'),
        'password' => env('HEALTH_CHECK_PASSWORD'),
    ],

    /**
     * Can define a list of connection names to test. Names can be
     * found in your config/database.php file. By default, we just
     * check the 'default' connection
     */
    'database' => [
        'connections' => ['default'],
    ],

    /**
     * Can give an array of required environment values, for example
     * 'REDIS_HOST'. If any don't exist, then it'll be surfaced in the
     * context of the healthcheck
     */
    'required-env' => [],

    /**
     * List of addresses and expected response codes to
     * monitor when running the HTTP health check
     *
     * e.g. address => response code
     */
    'addresses' => [],

    /**
     * Default response code for HTTP health check. Will be used
     * when one isn't provided in the addresses config.
     */
    'default-response-code' => 200,

    /**
     * Default timeout for cURL requests for HTTP health check.
     */
    'default-curl-timeout' => 2.0,

    /**
     * An array of other services that use the health check package
     * to hit. The URI should reference the endpoint specifically,
     * for example: https://api.example.com/health
     */
    'x-service-checks' => [],

    /**
     * A list of stores to be checked by the Cache health check
     */
    'cache' => [
        'stores' => [
            'array'
        ]
    ],

    /**
     * A list of disks to be checked by the Storage health check
     */
    'storage' => [
        'disks' => [
            'local',
        ]
    ],

    /**
     * Additional config can be put here. For example, a health check
     * for your .env file needs to know which keys need to be present.
     * You can pass this information by specifying a new key here then
     * accessing it via config('healthcheck.env') in your healthcheck class
     */
];

更新您的bootstrap/app.php文件以覆盖默认包配置

$app->configure('healthcheck');
中间件

您可以为访问/health端点的请求注册自定义中间件。您可以将以下内容添加到上面配置创建的config/healthcheck.php配置文件中,如下所示

/**
 * A list of middleware to run on the health-check route
 * It's recommended that you have a middleware that only
 * allows admin consumers to see the endpoint.
 *
 * See UKFast\HealthCheck\BasicAuth for a one-size-fits all
 * solution
 */
'middleware' => [
    App\Http\Middleware\CustomMiddleware::class
],

现在您的CustomMiddleware中间件将在每个请求到/health端点时运行。

开箱即用的健康检查包提供了

  • 基本认证 - 需要发送基本认证凭据才能查看完整状态
  • 添加标题 - 向响应中添加X-check-status标题,以便您无需解析JSON

检查

调度器健康检查

调度器健康检查通过在您的项目上使用每分钟有效期的缓存键来工作。您需要在项目的 Kernel.php 中注册 CacheSchedulerRunning 命令,以便每分钟运行一次。

您可以自定义缓存键和调度器停止运行前触发的错误的时间长度(分钟)。

$schedule->command(CacheSchedulerRunning::class)->everyMinute();

创建自己的健康检查

创建自己的健康检查非常简单。

在这个例子中,我们将创建一个Redis的健康检查。

首先,您需要创建自己的健康检查类,您可以将其放在 App\HealthChecks 目录下。在这个例子中,类将是 App\HealthChecks\RedisHealthCheck

每个健康检查都需要扩展基础 HealthCheck 类并实现一个 status() 方法。您还应该设置 $name 属性以便显示。

<?php

namespace App\HealthChecks;

use UKFast\HealthCheck\HealthCheck;

class RedisHealthCheck extends HealthCheck
{
    protected $name = 'my-fancy-redis-check';

    public function status()
    {
        return $this->okay();
    }
}

现在我们已经设置了基本类,我们可以在 config/healthcheck.php 文件中将它添加到要运行的检查列表中。

打开 config/healthcheck.php 文件,进入 'checks' 数组。将您的类添加到检查列表中

'checks' => [
    // ...
    App\HealthChecks\RedisHealthCheck::class,
]

如果您现在访问 /health 端点,您将看到 my-fancy-redis-check 属性,并且它应该返回状态 OK

现在我们可以开始正确实现检查了。

回到 RedisHealthCheck 类中的 status() 方法。

添加以下代码

public function status()
{
    try {
        Redis::ping();
    } catch (Exception $exception) {
        return $this->problem('Failed to connect to redis', [
            'exception' => $this->exceptionContext($exception),
        ]);
    }

    return $this->okay();
}

您还需要在顶部导入以下内容

use Illuminate\Support\Facades\Redis;
use UKFast\HealthCheck\HealthCheck;
use Exception;

最后,访问 /health 端点,根据您的应用程序是否真的可以连接到Redis,您将看到Redis的状态。如果它仍然返回 OK,请尝试将 REDIS_HOST 更改为一个不存在的地址以触发错误。

贡献

我们欢迎对社区有益的贡献。

您可以通过 open-source@ukfast.co.uk 联系我们的开源团队,他们将尽快回复您。

有关更多信息,请参阅我们的 CONTRIBUTING 文件。

安全

如果您认为您已经发现了安全漏洞,请通过 security@ukfast.co.uk 与我们的团队联系,他们将尽快回复您,而不是使用问题跟踪器。

许可

本项目采用 MIT 许可证(MIT)许可。请参阅 许可 文件以获取更多信息。