1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
|
import logging
from timeit import default_timer as timer
from django.utils.translation import gettext_lazy as _ # noqa: N812
from health_check.exceptions import HealthCheckException
logger = logging.getLogger("health-check")
class BaseHealthCheckBackend:
critical_service = True
"""
Define if service is critical to the operation of the site.
If set to ``True`` service failures return 500 response code on the
health check endpoint.
"""
def __init__(self):
self.errors = []
def check_status(self):
raise NotImplementedError
def run_check(self):
start = timer()
self.errors = []
try:
self.check_status()
except HealthCheckException as e:
self.add_error(e, e)
except BaseException:
logger.exception("Unexpected Error!")
raise
finally:
self.time_taken = timer() - start
def add_error(self, error, cause=None):
if isinstance(error, HealthCheckException):
pass
elif isinstance(error, str):
msg = error
error = HealthCheckException(msg)
else:
msg = _("unknown error")
error = HealthCheckException(msg)
if isinstance(cause, BaseException):
logger.exception(str(error))
else:
logger.error(str(error))
self.errors.append(error)
def pretty_status(self):
if self.errors:
return "\n".join(str(e) for e in self.errors)
return _("working")
@property
def status(self):
return int(not self.errors)
def identifier(self):
return self.__class__.__name__
|