ilyaplot/pulse

PHP的健康检查框架

2.0.2 2023-02-24 22:38 UTC

This package is auto-updated.

Last update: 2024-09-25 10:41:16 UTC


README

Pulse 允许您轻松编写应用程序的健康检查,并显示一个简单、汇总的报告,以便您可以快速诊断应用程序是否存在问题(或是否可以责怪其他人)。您还可以使用 nagioszabbix 等工具监控您的健康检查。

Packagist Version GitHub last commit Code Coverage Psalm Level Type Coverage Static Analysis Unit Tests Style CI PHP Version GitHub code size in bytes

等等,什么是健康检查?

健康检查是测试系统健康和与其他服务连接性的好方法。例如,您可以验证与 memcache 或 mysql 的连接性,您的应用程序是否可以读取/写入某些文件,或者第三方服务的 API 密钥是否仍然有效。

安装

您可以使用 composer 将此安装到您的项目中。在项目的根目录下创建一个 composer.json 文件,并添加以下内容

composer require ilyaplot/pulse

包含 vendor/autoload.php,然后就可以开始使用了!

警告

对于非关键检查,您可以使用警告,即使这些检查失败,您也会得到状态 200。使用这些检查来查看您的应用程序何时出现服务降级但仍可用。警告检查必须返回布尔值 truefalse

$pulse->addWarning(new ClosureRule(
    fn() => (new YoutubeClient())->isUp(),
    "Verify connectivity to youtube",
    LevelEnum::warning,
));

信息

$pulse->addInfo(new ClosureRule(
    fn() => (new YoutubeClient())->isUp(),
    "Verify connectivity to youtube", 
));

$pulse->addInfo(new ClosureRule(
    function(ClosureRule $closureRule) {
        $this->setErrorMessage( date('l'));
        return false;
    }, 
    "Today is",
));

$result = $pulse->run();

自定义规则

您还可以通过扩展 ilyaplot\pulse\rules\AbstractRule 类或实现 ilyaplot\pulse\rules\RuleInterface 来创建自己的自定义规则。例如,您可以创建一个检查应用程序是否可以连接到第三方服务的规则。

class YoutubeRule extends AbstractRule
{
    public function __construct(
        private readonly string $apiKey,
    ) {
        $this->description = 'Verify connectivity to youtube';
        $this->level = LevelEnum::warning;
    }
    
    public function run(): bool
    {
        $youtubeClient = new YoutubeClient($this->apiKey);
        try {
            return $youtubeClient->isUp(); // bool
        } catch (AuthenticationException) {
            $this->setErrorMessage('Invalid API key');
            return false;
        }
    }
}

然后您可以将它添加到您的健康检查中

$pulse->add(new YoutubeRule('your-api-key-1'));
$pulse->add(new YoutubeRule('your-api-key-2'));

示例

您可以在 examples/cli-usage.phpexamples/http-usage.php 中查看一些非常基本的示例健康检查。

$pulse = new ilyaplot\pulse\Pulse();

$pulse->add(new FileRule(
    '/path/to/your/config/file',
    description: "Check that config file is readable",
    checkIsReadable: true,
));

include '/path/to/your/config/file';

$pulse->addCritical(new ClosureRule(
    function() use ($config) {
        $memcache = new Memcache();
        if(!$memcache->connect($config['memcache_host'], $config['memcache_port'])){
            return false;
        }
        $key = 'healthcheck_test_key'
        $msg = 'memcache is working';
        $memcache->set($key, $msg);
        return $memcache->get($key) === $msg;
    }, 
    "Check memcache connectivity"
));

Pulse 是否与 X 兼容?

是的。Pulse 被设计成自包含且非常简单,因此它不需要您使用任何特定的框架。如果您选择,您可以包含其他东西,如 yml 解析器等,但我们建议不要在它上面添加完整的框架堆栈。如果由于某些原因框架无法加载,您的健康检查将不会显示,这意味着它们对诊断您遇到的问题没有用处。

这不会泄露有关我的应用程序的信息吗?

可能。您可能不希望将健康检查结果显示给公众。相反,您可以通过 whitelist certain IPs 来白名单特定的 IP。