# django-health-check
[](https://pypi.python.org/pypi/django-health-check/)
[](https://pypi.python.org/pypi/django-health-check/)
[](https://pypi.python.org/pypi/django-health-check/)
[](https://pypi.python.org/pypi/django-health-check/)
This project checks for various conditions and provides reports when anomalous
behavior is detected.
The following health checks are bundled with this project:
- cache
- database
- storage
- disk and memory utilization (via `psutil`)
- AWS S3 storage
- Celery task queue
- Celery ping
- RabbitMQ
- Migrations
Writing your own custom health checks is also very quick and easy.
We also like contributions, so don't be afraid to make a pull request.
## Use Cases
The primary intended use case is to monitor conditions via HTTP(S), with
responses available in HTML and JSON formats. When you get back a response that
includes one or more problems, you can then decide the appropriate course of
action, which could include generating notifications and/or automating the
replacement of a failing node with a new one. If you are monitoring health in a
high-availability environment with a load balancer that returns responses from
multiple nodes, please note that certain checks (e.g., disk and memory usage)
will return responses specific to the node selected by the load balancer.
## Supported Versions
We officially only support the latest version of Python as well as the
latest version of Django and the latest Django LTS version.
## Installation
First, install the `django-health-check` package:
```shell
$ pip install django-health-check
```
Add the health checker to a URL you want to use:
```python
urlpatterns = [
# ...
path(r'ht/', include('health_check.urls')),
]
```
Add the `health_check` applications to your `INSTALLED_APPS`:
```python
INSTALLED_APPS = [
# ...
'health_check', # required
'health_check.db', # stock Django health checkers
'health_check.cache',
'health_check.storage',
'health_check.contrib.migrations',
'health_check.contrib.celery', # requires celery
'health_check.contrib.celery_ping', # requires celery
'health_check.contrib.psutil', # disk and memory utilization; requires psutil
'health_check.contrib.s3boto3_storage', # requires boto3 and S3BotoStorage backend
'health_check.contrib.rabbitmq', # requires RabbitMQ broker
'health_check.contrib.redis', # requires Redis broker
]
```
**Note:** If using `boto 2.x.x` use `health_check.contrib.s3boto_storage`
(Optional) If using the `psutil` app, you can configure disk and memory
threshold settings; otherwise below defaults are assumed. If you want to disable
one of these checks, set its value to `None`.
```python
HEALTH_CHECK = {
'DISK_USAGE_MAX': 90, # percent
'MEMORY_MIN': 100, # in MB
}
```
To use Health Check Subsets, Specify a subset name and associate it with the relevant health check services to utilize Health Check Subsets.
```python
HEALTH_CHECK = {
# .....
"SUBSETS": {
"startup-probe": ["MigrationsHealthCheck", "DatabaseBackend"],
"liveness-probe": ["DatabaseBackend"],
"<SUBSET_NAME>": ["<Health_Check_Service_Name>"]
},
# .....
}
```
To only execute specific subset of health check
```shell
curl -X GET -H "Accept: application/json" http://www.example.com/ht/startup-probe/
```
If using the DB check, run migrations:
```shell
$ django-admin migrate
```
To use the RabbitMQ healthcheck, please make sure that there is a variable named
`BROKER_URL` on django.conf.settings with the required format to connect to your
rabbit server. For example:
```python
BROKER_URL = "amqp://myuser:mypassword@localhost:5672/myvhost"
```
To use the Redis healthcheck, please make sure that there is a variable named ``REDIS_URL``
on django.conf.settings with the required format to connect to your redis server. For example:
```python
REDIS_URL = "redis://localhost:6370"
```
The cache healthcheck tries to write and read a specific key within the cache backend.
It can be customized by setting `HEALTHCHECK_CACHE_KEY` to another value:
```python
HEALTHCHECK_CACHE_KEY = "custom_healthcheck_key"
```
## Setting up monitoring
You can use tools like Pingdom, StatusCake or other uptime robots to monitor service status.
The `/ht/` endpoint will respond with an HTTP 200 if all checks passed
and with an HTTP 500 if any of the tests failed.
Getting machine-readable JSON reports
If you want machine-readable status reports you can request the `/ht/`
endpoint with the `Accept` HTTP header set to `application/json`
or pass `format=json` as a query parameter.
The backend will return a JSON response:
```shell
$ curl -v -X GET -H "Accept: application/json" http://www.example.com/ht/
> GET /ht/ HTTP/1.1
> Host: www.example.com
> Accept: application/json
>
< HTTP/1.1 200 OK
< Content-Type: application/json
{
"CacheBackend": "working",
"DatabaseBackend": "working",
"S3BotoStorageHealthCheck": "working"
}
$ curl -v -X GET http://www.example.com/ht/?format=json
> GET /ht/?format=json HTTP/1.1
> Host: www.example.com
>
< HTTP/1.1 200 OK
< Content-Type: application/json
{
"CacheBackend": "working",
"DatabaseBackend": "working",
"S3BotoStorageHealthCheck": "working"
}
```
## Writing a custom health check
Writing a health check is quick and easy:
```python
from health_check.backends import BaseHealthCheckBackend
class MyHealthCheckBackend(BaseHealthCheckBackend):
#: The status endpoints will respond with a 200 status code
#: even if the check errors.
critical_service = False
def check_status(self):
# The test code goes here.
# You can use `self.add_error` or
# raise a `HealthCheckException`,
# similar to Django's form validation.
pass
def identifier(self):
return self.__class__.__name__ # Display name on the endpoint.
```
After writing a custom checker, register it in your app configuration:
```python
from django.apps import AppConfig
from health_check.plugins import plugin_dir
class MyAppConfig(AppConfig):
name = 'my_app'
def ready(self):
from .backends import MyHealthCheckBackend
plugin_dir.register(MyHealthCheckBackend)
```
Make sure the application you write the checker into is registered in your
`INSTALLED_APPS`.
## Customizing output
You can customize HTML or JSON rendering by inheriting from `MainView` in
`health_check.views` and customizing the `template_name`, `get`, `render_to_response`
and `render_to_response_json` properties:
```python
# views.py
from health_check.views import MainView
class HealthCheckCustomView(MainView):
template_name = 'myapp/health_check_dashboard.html' # customize the used templates
def get(self, request, *args, **kwargs):
plugins = []
status = 200 # needs to be filled status you need
# ...
if 'application/json' in request.META.get('HTTP_ACCEPT', ''):
return self.render_to_response_json(plugins, status)
return self.render_to_response(plugins, status)
def render_to_response(self, plugins, status): # customize HTML output
return HttpResponse('COOL' if status == 200 else 'SWEATY', status=status)
def render_to_response_json(self, plugins, status): # customize JSON output
return JsonResponse(
{str(p.identifier()): 'COOL' if status == 200 else 'SWEATY' for p in plugins},
status=status
)
# urls.py
import views
urlpatterns = [
# ...
path(r'ht/', views.HealthCheckCustomView.as_view(), name='health_check_custom'),
]
```
## Django command
You can run the Django command `health_check` to perform your health checks via the command line,
or periodically with a cron, as follow:
```shell
django-admin health_check
```
This should yield the following output:
```
DatabaseHealthCheck ... working
CustomHealthCheck ... unavailable: Something went wrong!
```
Similar to the http version, a critical error will cause the command to quit with the exit code `1`.
## Other resources
- [django-watchman](https://github.com/mwarkentin/django-watchman) is a package that does some of the same things in a slightly different way.
Raw data
{
"_id": null,
"home_page": "https://github.com/revsys/django-health-check",
"name": "django-health-check",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.8",
"maintainer_email": null,
"keywords": "django, postgresql",
"author": "Kristian Ollegaard",
"author_email": "kristian@oellegaard.com",
"download_url": "https://files.pythonhosted.org/packages/66/e9/0699ea3debfda75e5960ff99f56974136380e6f8202d453de7357e1f67fc/django_health_check-3.18.3.tar.gz",
"platform": null,
"description": "# django-health-check\n\n[](https://pypi.python.org/pypi/django-health-check/)\n[](https://pypi.python.org/pypi/django-health-check/)\n[](https://pypi.python.org/pypi/django-health-check/)\n[](https://pypi.python.org/pypi/django-health-check/)\n\n\nThis project checks for various conditions and provides reports when anomalous\nbehavior is detected.\n\nThe following health checks are bundled with this project:\n\n- cache\n- database\n- storage\n- disk and memory utilization (via `psutil`)\n- AWS S3 storage\n- Celery task queue\n- Celery ping\n- RabbitMQ\n- Migrations\n\nWriting your own custom health checks is also very quick and easy.\n\nWe also like contributions, so don't be afraid to make a pull request.\n\n## Use Cases\n\nThe primary intended use case is to monitor conditions via HTTP(S), with\nresponses available in HTML and JSON formats. When you get back a response that\nincludes one or more problems, you can then decide the appropriate course of\naction, which could include generating notifications and/or automating the\nreplacement of a failing node with a new one. If you are monitoring health in a\nhigh-availability environment with a load balancer that returns responses from\nmultiple nodes, please note that certain checks (e.g., disk and memory usage)\nwill return responses specific to the node selected by the load balancer.\n\n## Supported Versions\n\nWe officially only support the latest version of Python as well as the\nlatest version of Django and the latest Django LTS version.\n\n## Installation\n\nFirst, install the `django-health-check` package:\n\n```shell\n$ pip install django-health-check\n```\n\nAdd the health checker to a URL you want to use:\n\n```python\n urlpatterns = [\n # ...\n path(r'ht/', include('health_check.urls')),\n ]\n```\n\nAdd the `health_check` applications to your `INSTALLED_APPS`:\n\n```python\n INSTALLED_APPS = [\n # ...\n 'health_check', # required\n 'health_check.db', # stock Django health checkers\n 'health_check.cache',\n 'health_check.storage',\n 'health_check.contrib.migrations',\n 'health_check.contrib.celery', # requires celery\n 'health_check.contrib.celery_ping', # requires celery\n 'health_check.contrib.psutil', # disk and memory utilization; requires psutil\n 'health_check.contrib.s3boto3_storage', # requires boto3 and S3BotoStorage backend\n 'health_check.contrib.rabbitmq', # requires RabbitMQ broker\n 'health_check.contrib.redis', # requires Redis broker\n ]\n```\n\n**Note:** If using `boto 2.x.x` use `health_check.contrib.s3boto_storage`\n\n(Optional) If using the `psutil` app, you can configure disk and memory\nthreshold settings; otherwise below defaults are assumed. If you want to disable\none of these checks, set its value to `None`.\n\n```python\n HEALTH_CHECK = {\n 'DISK_USAGE_MAX': 90, # percent\n 'MEMORY_MIN': 100, # in MB\n }\n```\n\nTo use Health Check Subsets, Specify a subset name and associate it with the relevant health check services to utilize Health Check Subsets.\n```python\n HEALTH_CHECK = {\n # .....\n \"SUBSETS\": {\n \"startup-probe\": [\"MigrationsHealthCheck\", \"DatabaseBackend\"],\n \"liveness-probe\": [\"DatabaseBackend\"],\n \"<SUBSET_NAME>\": [\"<Health_Check_Service_Name>\"]\n },\n # .....\n }\n```\n\nTo only execute specific subset of health check\n```shell\ncurl -X GET -H \"Accept: application/json\" http://www.example.com/ht/startup-probe/\n```\n\nIf using the DB check, run migrations:\n\n```shell\n$ django-admin migrate\n```\n\nTo use the RabbitMQ healthcheck, please make sure that there is a variable named\n`BROKER_URL` on django.conf.settings with the required format to connect to your\nrabbit server. For example:\n\n```python\n BROKER_URL = \"amqp://myuser:mypassword@localhost:5672/myvhost\"\n```\n\nTo use the Redis healthcheck, please make sure that there is a variable named ``REDIS_URL``\non django.conf.settings with the required format to connect to your redis server. For example:\n\n```python\n REDIS_URL = \"redis://localhost:6370\"\n```\n\nThe cache healthcheck tries to write and read a specific key within the cache backend.\nIt can be customized by setting `HEALTHCHECK_CACHE_KEY` to another value:\n\n```python\n HEALTHCHECK_CACHE_KEY = \"custom_healthcheck_key\"\n```\n\n## Setting up monitoring\n\nYou can use tools like Pingdom, StatusCake or other uptime robots to monitor service status.\nThe `/ht/` endpoint will respond with an HTTP 200 if all checks passed\nand with an HTTP 500 if any of the tests failed.\nGetting machine-readable JSON reports\n\nIf you want machine-readable status reports you can request the `/ht/`\nendpoint with the `Accept` HTTP header set to `application/json`\nor pass `format=json` as a query parameter.\n\nThe backend will return a JSON response:\n\n```shell\n $ curl -v -X GET -H \"Accept: application/json\" http://www.example.com/ht/\n\n > GET /ht/ HTTP/1.1\n > Host: www.example.com\n > Accept: application/json\n >\n < HTTP/1.1 200 OK\n < Content-Type: application/json\n\n {\n \"CacheBackend\": \"working\",\n \"DatabaseBackend\": \"working\",\n \"S3BotoStorageHealthCheck\": \"working\"\n }\n\n $ curl -v -X GET http://www.example.com/ht/?format=json\n\n > GET /ht/?format=json HTTP/1.1\n > Host: www.example.com\n >\n < HTTP/1.1 200 OK\n < Content-Type: application/json\n\n {\n \"CacheBackend\": \"working\",\n \"DatabaseBackend\": \"working\",\n \"S3BotoStorageHealthCheck\": \"working\"\n }\n```\n\n## Writing a custom health check\n\nWriting a health check is quick and easy:\n\n```python\n from health_check.backends import BaseHealthCheckBackend\n\n class MyHealthCheckBackend(BaseHealthCheckBackend):\n #: The status endpoints will respond with a 200 status code\n #: even if the check errors.\n critical_service = False\n\n def check_status(self):\n # The test code goes here.\n # You can use `self.add_error` or\n # raise a `HealthCheckException`,\n # similar to Django's form validation.\n pass\n\n def identifier(self):\n return self.__class__.__name__ # Display name on the endpoint.\n```\n\nAfter writing a custom checker, register it in your app configuration:\n\n```python\n from django.apps import AppConfig\n\n from health_check.plugins import plugin_dir\n\n class MyAppConfig(AppConfig):\n name = 'my_app'\n\n def ready(self):\n from .backends import MyHealthCheckBackend\n plugin_dir.register(MyHealthCheckBackend)\n```\n\nMake sure the application you write the checker into is registered in your\n`INSTALLED_APPS`.\n\n## Customizing output\n\nYou can customize HTML or JSON rendering by inheriting from `MainView` in\n`health_check.views` and customizing the `template_name`, `get`, `render_to_response`\nand `render_to_response_json` properties:\n\n```python\n # views.py\n from health_check.views import MainView\n\n class HealthCheckCustomView(MainView):\n template_name = 'myapp/health_check_dashboard.html' # customize the used templates\n\n def get(self, request, *args, **kwargs):\n plugins = []\n status = 200 # needs to be filled status you need\n # ...\n if 'application/json' in request.META.get('HTTP_ACCEPT', ''):\n return self.render_to_response_json(plugins, status)\n return self.render_to_response(plugins, status)\n\n def render_to_response(self, plugins, status): # customize HTML output\n return HttpResponse('COOL' if status == 200 else 'SWEATY', status=status)\n\n def render_to_response_json(self, plugins, status): # customize JSON output\n return JsonResponse(\n {str(p.identifier()): 'COOL' if status == 200 else 'SWEATY' for p in plugins},\n status=status\n )\n\n # urls.py\n import views\n\n urlpatterns = [\n # ...\n path(r'ht/', views.HealthCheckCustomView.as_view(), name='health_check_custom'),\n ]\n```\n\n## Django command\n\nYou can run the Django command `health_check` to perform your health checks via the command line,\nor periodically with a cron, as follow:\n\n```shell\n django-admin health_check\n```\n\nThis should yield the following output:\n\n```\n DatabaseHealthCheck ... working\n CustomHealthCheck ... unavailable: Something went wrong!\n```\n\nSimilar to the http version, a critical error will cause the command to quit with the exit code `1`.\n\n\n## Other resources\n\n- [django-watchman](https://github.com/mwarkentin/django-watchman) is a package that does some of the same things in a slightly different way.\n",
"bugtrack_url": null,
"license": "MIT License",
"summary": "Run checks on services like databases, queue servers, celery processes, etc.",
"version": "3.18.3",
"project_urls": {
"Homepage": "https://github.com/revsys/django-health-check"
},
"split_keywords": [
"django",
" postgresql"
],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "e21e3b23b580762cca7456427731de9b90718d15eec02ebe096437469d767dfe",
"md5": "8a99cc4b5b29f6b784064b950f49707f",
"sha256": "f5f58762b80bdf7b12fad724761993d6e83540f97e2c95c42978f187e452fa07"
},
"downloads": -1,
"filename": "django_health_check-3.18.3-py2.py3-none-any.whl",
"has_sig": false,
"md5_digest": "8a99cc4b5b29f6b784064b950f49707f",
"packagetype": "bdist_wheel",
"python_version": "py2.py3",
"requires_python": ">=3.8",
"size": 30331,
"upload_time": "2024-06-22T14:34:30",
"upload_time_iso_8601": "2024-06-22T14:34:30.184679Z",
"url": "https://files.pythonhosted.org/packages/e2/1e/3b23b580762cca7456427731de9b90718d15eec02ebe096437469d767dfe/django_health_check-3.18.3-py2.py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "66e90699ea3debfda75e5960ff99f56974136380e6f8202d453de7357e1f67fc",
"md5": "5bf39970fa439c11030109683f411893",
"sha256": "18b75daca4551c69a43f804f9e41e23f5f5fb9efd06cf6a313b3d5031bb87bd0"
},
"downloads": -1,
"filename": "django_health_check-3.18.3.tar.gz",
"has_sig": false,
"md5_digest": "5bf39970fa439c11030109683f411893",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.8",
"size": 20919,
"upload_time": "2024-06-22T14:34:32",
"upload_time_iso_8601": "2024-06-22T14:34:32.627257Z",
"url": "https://files.pythonhosted.org/packages/66/e9/0699ea3debfda75e5960ff99f56974136380e6f8202d453de7357e1f67fc/django_health_check-3.18.3.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2024-06-22 14:34:32",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "revsys",
"github_project": "django-health-check",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"lcname": "django-health-check"
}