Creating custom checks | laravel-health-rust | Spatie       

 SPATIE  

laravel-health-rust
===================

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Laravel-health-rust](https://spatie.be/docs/laravel-health-rust/v1)  Basic-usage  Creating custom checks

 Version   v1      

 Other versions for crawler [v1](https://spatie.be/docs/laravel-health-rust/v1) 

  Creating custom checks    
- [ Introduction ](https://spatie.be/docs/laravel-health-rust/v1/introduction)
- [ Support us ](https://spatie.be/docs/laravel-health-rust/v1/support-us)
- [ Requirements ](https://spatie.be/docs/laravel-health-rust/v1/requirements)
- [ Installation &amp; setup ](https://spatie.be/docs/laravel-health-rust/v1/installation-setup)
- [ Questions and issues ](https://spatie.be/docs/laravel-health-rust/v1/questions-issues)
- [ Changelog ](https://spatie.be/docs/laravel-health-rust/v1/changelog)
- [ Testing ](https://spatie.be/docs/laravel-health-rust/v1/testing)
- [ About us ](https://spatie.be/docs/laravel-health-rust/v1/about-us)

Usage
-----

- [ Registering your first check ](https://spatie.be/docs/laravel-health-rust/v1/basic-usage/registering-your-first-check)
- [ Creating custom checks ](https://spatie.be/docs/laravel-health-rust/v1/basic-usage/creating-custom-checks)
- [ Manually running checks ](https://spatie.be/docs/laravel-health-rust/v1/basic-usage/manually-running-checks)
- [ Conditionally running or modifying checks ](https://spatie.be/docs/laravel-health-rust/v1/basic-usage/conditionally-running-or-modifying-checks)
- [ Endpoints ](https://spatie.be/docs/laravel-health-rust/v1/basic-usage/endpoints)
- [ Pausing and resuming checks ](https://spatie.be/docs/laravel-health-rust/v1/basic-usage/pausing-and-resuming-checks)
- [ Registering the same check multiple times ](https://spatie.be/docs/laravel-health-rust/v1/basic-usage/registering-the-same-check-multiple-times)
- [ Testing ](https://spatie.be/docs/laravel-health-rust/v1/basic-usage/testing)

Storing results
---------------

- [ General ](https://spatie.be/docs/laravel-health-rust/v1/storing-results/general)
- [ As JSON ](https://spatie.be/docs/laravel-health-rust/v1/storing-results/in-a-json-file)
- [ In the cache ](https://spatie.be/docs/laravel-health-rust/v1/storing-results/in-cache)
- [ In the database ](https://spatie.be/docs/laravel-health-rust/v1/storing-results/in-the-database)
- [ Not storing results ](https://spatie.be/docs/laravel-health-rust/v1/storing-results/not-storing-results)

Configuring notifications
-------------------------

- [ General ](https://spatie.be/docs/laravel-health-rust/v1/configuring-notifications/general)
- [ Via mail ](https://spatie.be/docs/laravel-health-rust/v1/configuring-notifications/via-mail)
- [ Via Slack ](https://spatie.be/docs/laravel-health-rust/v1/configuring-notifications/via-slack)
- [ Via Microsoft Teams ](https://spatie.be/docs/laravel-health-rust/v1/configuring-notifications/via-teams)
- [ Via Oh Dear ](https://spatie.be/docs/laravel-health-rust/v1/configuring-notifications/via-oh-dear)

Viewing check results
---------------------

- [ General ](https://spatie.be/docs/laravel-health-rust/v1/viewing-results/general)
- [ On a webpage ](https://spatie.be/docs/laravel-health-rust/v1/viewing-results/on-a-webpage)
- [ On the CLI ](https://spatie.be/docs/laravel-health-rust/v1/viewing-results/on-the-cli)
- [ As JSON ](https://spatie.be/docs/laravel-health-rust/v1/viewing-results/as-json)

Available checks
----------------

- [ Overview ](https://spatie.be/docs/laravel-health-rust/v1/available-checks/overview)
- [ Backups ](https://spatie.be/docs/laravel-health-rust/v1/available-checks/backups)
- [ Application Cache ](https://spatie.be/docs/laravel-health-rust/v1/available-checks/cache)
- [ Cached config, routes, and events ](https://spatie.be/docs/laravel-health-rust/v1/available-checks/cached-config-routes-and-events)
- [ CPU load ](https://spatie.be/docs/laravel-health-rust/v1/available-checks/cpu-load)
- [ DB connection ](https://spatie.be/docs/laravel-health-rust/v1/available-checks/db-connection)
- [ DB connection count ](https://spatie.be/docs/laravel-health-rust/v1/available-checks/db-connection-count)
- [ DB size ](https://spatie.be/docs/laravel-health-rust/v1/available-checks/db-size-check)
- [ DB table size ](https://spatie.be/docs/laravel-health-rust/v1/available-checks/db-table-size-check)
- [ Debug mode ](https://spatie.be/docs/laravel-health-rust/v1/available-checks/debug-mode)
- [ Environment ](https://spatie.be/docs/laravel-health-rust/v1/available-checks/environment)
- [ Flare error count ](https://spatie.be/docs/laravel-health-rust/v1/available-checks/flare-error-count)
- [ Horizon ](https://spatie.be/docs/laravel-health-rust/v1/available-checks/horizon)
- [ Meilisearch ](https://spatie.be/docs/laravel-health-rust/v1/available-checks/meilisearch)
- [ Ping ](https://spatie.be/docs/laravel-health-rust/v1/available-checks/ping)
- [ Queue ](https://spatie.be/docs/laravel-health-rust/v1/available-checks/queue)
- [ Redis ](https://spatie.be/docs/laravel-health-rust/v1/available-checks/redis)
- [ Redis memory usage ](https://spatie.be/docs/laravel-health-rust/v1/available-checks/redis-memory-usage)
- [ Reverb ](https://spatie.be/docs/laravel-health-rust/v1/available-checks/reverb)
- [ Schedule ](https://spatie.be/docs/laravel-health-rust/v1/available-checks/schedule)
- [ Security advisories ](https://spatie.be/docs/laravel-health-rust/v1/available-checks/security-advisories)
- [ Used disk space ](https://spatie.be/docs/laravel-health-rust/v1/available-checks/used-disk-space)

Security
--------

- [ Using Secret Token ](https://spatie.be/docs/laravel-health-rust/v1/security/using-secret-token)

 Creating custom checks
======================

###  On this page 

1. [ Creating results ](#content-creating-results)
2. [ Lifecycle hooks ](#content-lifecycle-hooks)
3. [ Adding a short summary ](#content-adding-a-short-summary)
4. [ Adding meta information ](#content-adding-meta-information)

This package offers [a few common checks](../available-checks/overview) out of the box. If you want to monitor another aspect of your app, you can create your own custom check.

A check is any type that implements `Check`. Give it a default name and implement `run`.

```
use spatie_health::{Check, CheckResult, Context, Result};

struct YourCustomCheck;

impl Check for YourCustomCheck {
    fn default_name(&self) -> &'static str { "YourCustomCheck" }

    fn run(&self, _ctx: &Context<'_>) -> Result<CheckResult> {
        Ok(CheckResult::make().ok(""))
    }
}
```

<a id="creating-results"></a>

Creating results
--------------------------------------------------------------------------------------------------------

The `run` method should always return a `Result<CheckResult>`. Using this object you can instruct the package to report a failure, to send a notification, and add meta information. Return an error if the check could not complete.

### Handling errors

- Return `Ok(CheckResult::make().failed(message))` for a detected health problem.
- Propagate probe errors with `?`. The runner reports them privately and records a `crashed` result without exposing their messages.
- Match registration errors by variant rather than parsing text. Registration is atomic: a rejected batch adds no checks.
- Cron, date, glob, I/O, JSON, HTTP and SMTP errors retain their original error types. `Error::Framework` retains Laravel's reportable error.

```
use spatie_health::{Check, Error, Health, checks::CacheCheck};

let mut health = Health::new();
health.checks([CacheCheck::new().registered()])?;

let error = health.checks([CacheCheck::new().registered()]);
assert!(matches!(error, Err(Error::DuplicateCheckName(name)) if name == "Cache"));
assert_eq!(health.registered_checks().len(), 1);
```

### Setting a status and sending notifications

The `CheckResult` object has a `status` to signify a check is ok, produces a warning, or has failed.

You can use these methods to set the `status` of a result:

```
use spatie_health::CheckResult;

let mut result = CheckResult::make();

result = result.ok("");
result = result.warning("");
result = result.failed("");
```

You should call `ok` when everything your check verifies is ok. You should call `failed` if you detected that there was something wrong. The `warning` should be used when the check did pass, but might fail soon.

When you pass a nonempty string to any of these methods and return that result, then the package can send a notification through your configured channels.

Here's an example check that will check for used disk space. When used disk space is above 70%, a warning notification will be sent, when above 90% an error notification will be sent.

```
use spatie_health::{Check, CheckResult, Context, Result};

struct UsedDiskSpaceCheck;

impl Check for UsedDiskSpaceCheck {
    fn default_name(&self) -> &'static str { "UsedDiskSpace" }

    fn run(&self, _ctx: &Context<'_>) -> Result<CheckResult> {
        let used_disk_space_percentage = self.get_disk_usage_percentage()?;

        let result = CheckResult::make();

        if used_disk_space_percentage > 90 {
            return Ok(result.failed(format!("The disk is almost full ({used_disk_space_percentage} % used)")));
        }

        if used_disk_space_percentage > 70 {
            return Ok(result.warning(format!("The disk getting full ({used_disk_space_percentage}% used)")));
        }

        Ok(result.ok(""))
    }
}

impl UsedDiskSpaceCheck {
    fn get_disk_usage_percentage(&self) -> Result<u64> {
        let total = fs2::total_space(".")?;
        let available = fs2::available_space(".")?;
        Ok((total - available) * 100 / total)
    }
}
```

Lifecycle hooks
-----------------------------------------------------------------------------------------------------

Register native event listeners for `events::CheckStarting`, `events::CheckEnded` and `integration::HealthChecked`. Starting and ended events fire only for checks that run. The ended event contains the finalized result, including a crashed status when a probe returns an error. The completed event fires after persistence and notifications for command, HTTP and direct runner invocations. A paused runner emits none of these events.

Custom checks can implement `Check::on_terminate`. Call `Health::terminate(request, response)` explicitly from an application lifecycle hook, passing JSON context that your checks understand. Laravel 0.1.0 has no automatic after-response termination callback; this package does not emulate one. Rust panics are not caught. Probe errors are reported through `laravel::report` without exposing their private details in public results.

Adding a short summary
--------------------------------------------------------------------------------------------------------------------------

Optionally, you can add a short summary of what the check found, using the `short_summary` method.

```
use spatie_health::{Check, CheckResult, Context, Result};

struct UsedDiskSpaceCheck;

impl Check for UsedDiskSpaceCheck {
    fn default_name(&self) -> &'static str { "UsedDiskSpace" }

    fn run(&self, _ctx: &Context<'_>) -> Result<CheckResult> {
        let used_disk_space_percentage = self.get_disk_usage_percentage()?;

        let result = CheckResult::make();
        let result = result.short_summary(format!("{used_disk_space_percentage}%"));

        Ok(result)
    }
}

impl UsedDiskSpaceCheck {
    fn get_disk_usage_percentage(&self) -> Result<u64> {
        let total = fs2::total_space(".")?;
        let available = fs2::available_space(".")?;
        Ok((total - available) * 100 / total)
    }
}
```

This short summary will be written in [a result store](../storing-results/general). The summary can be used when displaying all the results on a dashboard.

Adding meta information
-----------------------------------------------------------------------------------------------------------------------------

You can add meta information to a result. This meta information will be written in [a result store](../storing-results/general). By adding meta information, external services like Oh Dear can display it in their notification, or you can keep a history of this meta information in your own database.

Meta information can be added to a check result by calling `meta` and passing it a JSON value.

```
use spatie_health::{Check, CheckResult, Context, Result};

struct UsedDiskSpaceCheck;

impl Check for UsedDiskSpaceCheck {
    fn default_name(&self) -> &'static str { "UsedDiskSpace" }

    fn run(&self, _ctx: &Context<'_>) -> Result<CheckResult> {
        let used_disk_space_percentage = self.get_disk_usage_percentage()?;

        let result = CheckResult::make();
        let result = result.meta(serde_json::json!({"used_disk_space": used_disk_space_percentage}));

        Ok(result)
    }
}

impl UsedDiskSpaceCheck {
    fn get_disk_usage_percentage(&self) -> Result<u64> {
        let total = fs2::total_space(".")?;
        let available = fs2::available_space(".")?;
        Ok((total - available) * 100 / total)
    }
}
```

 A good
match?
-------------

### What we do best

- All things Laravel
- Custom frontend components
- Building APIs
- AI-powered features
- Simplifying things
- Clean solutions
- Integrating services

### Not our cup of tea

- WordPress themes
- Cutting corners
- Free mockups to win a job
- "Just execute the briefing"

 In short: we'd like to be a **substantial part** of your project.

 [ Get in touch via email ](mailto:info@spatie.be?subject=A%20good%20match%21&body=Tell%20us%20as%20much%20as%20you%20can%20about%0A-%20your%20online%20project%0A-%20your%20planning%0A-%20your%20budget%0A-%20%E2%80%A6%0A%0AAnything%20that%20helps%20us%20to%20start%20straightforward%21)
