generationtux/healthz 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

generationtux/healthz

Composer 安装命令:

composer require generationtux/healthz

包简介

Health checks for PHP apps.

README 文档

README

Build Test Status Code Climate Test Coverage

PHP Healthz

Health checking for PHP apps with built-in support for Laravel.

Requirements

  • PHP 8.2 - 8.4
  • Laravel 10.x - 12.x (for Laravel integration)

Get an easy overview of the health of your app! Implement a health check endpoint for load balancers, or your own sanity :) Comes with an optional UI and set of pre-configured checks you can use, and is extensible to add custom health checks to the stack as well.

Setup

$ composer require generationtux/healthz

Laravel < 5.4

(the following should work with Lumen as well, with minor differences)

Add the service provider that will register the default health checks and routes

// config/app.php
'providers' => [
    Illuminate...,
    Gentux\Healthz\Support\HealthzServiceProvider::class,
]

You should be able to visit /healthz/ui to see the default Laravel health checks, or run php artisan healthz to get a CLI view.

To add basic auth to the UI page, set the HEALTHZ_USERNAME and HEALTHZ_PASSWORD environment variables. Even if the UI has basic auth, the simplified /healthz endpoint will always be available to respond with a simple ok or fail for load balancers and other automated checks to hit.

In order to customize the health checks, simply register Gentux\Healthz\Healthz in your app service provider (probably app/Providers/AppServiceProvider.php) to build a custom Healthz instance.

use Gentux\Healthz\Healthz;
use Illuminate\Support\ServiceProvider;
use Gentux\Healthz\Checks\General\EnvHealthCheck;
use Gentux\Healthz\Checks\Laravel\DatabaseHealthCheck;

class AppServiceProvider extends ServiceProvider
{
        public function register()
        {
                $this->app->bind(Healthz::class, function () {
                        $env = new EnvHealthCheck();
                        $db = new DatabaseHealthCheck();
                        $db->setConnection("non-default");

                        return new Healthz([$env, $db]);
                });
        }
}

See more about configuring available checks

General PHP

Build an instance of the health check

<?php
use Gentux\Healthz\Healthz;
use Gentux\Healthz\Checks\General\MemcachedHealthCheck;

$memcached = (new MemcachedHealthCheck())->addServer("127.0.0.1");
$healthz = new Healthz([$memcached]);

Run the checks and review results

// @var $results Gentux\Healthz\ResultStack
$results = $healthz->run();

if ($results->hasFailures()) {
        // oh no
}

if ($results->hasWarnings()) {
        // hmm
}

foreach ($results->all() as $result) {
        // @var $result Gentux\Healthz\HealthResult
        if ($result->passed() || $result->warned() || $result->failed()) {
                echo "it did one of those things at least";
        }

        echo "{$result->title()}: {$result->status()} ({$result->description()})";
}

Get the UI view

$html = $healthz->html();

Enable integration with the Laravel Exception Handler

It allows to report Healthz failure and warning exceptions to the Laravel log exceptions or send them to an external service like Flare, Bugsnag or Sentry.

This feature is disabled by default, here how to enable it for Healthz failure and warning exceptions:

$healthz->setReportFailure(true);
$healthz->setReportWarning(true);

NOTE: The report() Laravel helper must be present, otherwise this feature does nothing

For more informations see the Laravel Docs: https://laravel.com/docs/8.x/errors

Check configuration

HTTP

Create a new Guzzle Request to pass to the constuctor of the HTTP health check.

use GuzzleHTTP\PSR7\Request;
use Gentux\Healthz\Checks\General\HttpHealthCheck;

$request = new Request("GET", "http://example.com");
$httpCheck = new HttpHealthCheck($request);

You can optionally pass the expected response status code (defaults to 200), as well as Guzzle client options.

$httpCheck = new HttpHealthCheck($request, 204, [
        "base_url" => "http://example.com",
]);

Memcached

Create a new Memcached health check and use the methods addServer and setOptions.

use Gentux\Healthz\Checks\General\MemcachedHealthCheck;

$memcachedCheck = new MemcachedHealthCheck();
$memcachedCheck->addServer($server, $port = 11211, $weight = 0);
$memcachedCheck->setOptions([]);

See Memcached setOptions for option information.

Debug

Set the environment variable to check if the app is running in debug. If this check fails, it emits a warning.

use Gentux\Healthz\Checks\General\DebugHealthCheck;

$debugCheck = new DebugHealthCheck("APP_DEBUG");

In this case, if APP_DEBUG == 'true' then this check will emit a warning.

Env

Provide an environment variable name to check for the apps environment. If the provided env name is found the check will always be successful and simply output the name. If no environment variable is set the check will emit a warning.

use Gentux\Healthz\Checks\General\EnvHealthCheck;

$envCheck = new EnvHealthCheck("APP_ENV");

Database (Laravel)

This will use Laravel's built in database service to verify connectivity. You may optionally set a connection name to use (will use the default if not provided).

use Gentux\Healthz\Checks\Laravel\DatabaseHealthCheck;

$dbCheck = new DatabaseHealthCheck();
$dbCheck->setConnection("my_conn"); // optional

Queue (Laravel)

The queue health check currently supports sync and sqs queues. You may optionally set the queue name to use (will use the default if not specified).

use Gentux\Healthz\Checks\Laravel\QueueHealthCheck;

$queueCheck = new QueueHealthCheck();
$queueCheck->setName("my_queue"); // optional

Custom checks

Note: Checks may have one of 3 statuses (success, warning, or failure). Any combination of success and warning and the stack as a whole will be considered to be successful. Any single failure, however, will consider the stack to be failed.

To create a custom health check, you should extend Gentux\Healthz\HealthCheck and implement the one abstract method run().

<?php

use Gentux\Healthz\HealthCheck;

class MyCustomCheck extends HealthCheck
{
        /** @var string Optionally set a title, otherwise the class name will be used */
        protected $title = "";

        /** @var string Optionally set a description, just to provide more info on the UI */
        protected $description = "";

        public function run()
        {
                // any exception that is thrown will consider the check unhealthy
        }
}

If no exception is thrown, the check will be presumed to have been successful. Otherwise, the exception's message will be used as the status of the failed check.

public function run()
{
    throw new Exception('Heres why the check failed.');
}

If you would like the check to show a warning instead of a full failure, throw an instance of Gentux\Healthz\Exceptions\HealthWarningException.

use Gentux\Healthz\Exceptions\HealthWarningException;

public function run()
{
    throw new HealthWarningException("The check didn't fail, but here ye be warned.");
}

Development

Running Tests Locally

Run tests on default PHP version (8.4):

docker-compose run --rm php composer install
docker-compose run --rm php ./vendor/bin/phpunit

Run tests on a specific PHP version:

PHP_VERSION=8.2 docker-compose build php
PHP_VERSION=8.2 docker-compose run --rm php composer install
PHP_VERSION=8.2 docker-compose run --rm php ./vendor/bin/phpunit

CI Matrix

PHP Laravel 10 Laravel 11 Laravel 12
8.2
8.3
8.4

Contributing

Make your changes and add any needed tests around said changes. Then open a pull request into the generationtux repository.

generationtux/healthz 适用场景与选型建议

generationtux/healthz 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 40.75k 次下载、GitHub Stars 达 26, 最近一次更新时间为 2016 年 03 月 09 日, 在 PHP 生态内属于活跃度较高的组件。

我们在过去多个企业项目中使用过 generationtux/healthz 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 generationtux/healthz 我们能提供哪些服务?
定制开发 / 二次开发

基于 generationtux/healthz 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 40.75k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 26
  • 点击次数: 10
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 26
  • Watchers: 20
  • Forks: 5
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2016-03-09