Package: django-watchman
django-watchmandjango-watchman exposes a status endpoint for your backing services like
databases, caches, etc.DocumentationThe full documentation is athttp://django-watchman.rtfd.org.TestimonialsWe’re in love with django-watchman. External monitoring is a vital part of our service offering. Using django-watchman we can introspect the infrastructure of an application via a secure URL. It’s very well written and easy to extend. We’ve recommended it to many of our clients already.— Hany Fahim, CEO,VM Farms.QuickstartInstalldjango-watchman:pip install django-watchmanAddwatchmanto yourINSTALLED_APPSsetting like this:INSTALLED_APPS = (
    ...
    'watchman',
)Include the watchman URLconf in your projecturls.pylike this:re_path(r'^watchman/', include('watchman.urls')),Start the development server and visithttp://127.0.0.1:8000/watchman/to
get a JSON response of your backing service statuses:{
    "databases": [
        {
            "default": {
                "ok": true
            }
        }
    ],
    "caches": [
        {
            "default": {
                "ok": true
            }
        }
    ],
    "storage": {"ok": true}
}Pycon Canada Presentation (10 minutes)FeaturesHuman-friendly dashboardVisithttp://127.0.0.1:8000/watchman/dashboard/to get a human-friendly HTML
representation of all of your watchman checks.Token based authenticationIf you want to protect the status endpoint, you can use theWATCHMAN_TOKENSsetting.
This is a comma-separated list of tokens.
When this setting is added, you must pass one of the tokens in as thewatchman-tokenGETparameter:GET http://127.0.0.1:8000/watchman/?watchman-token=:tokenOr by setting theAuthorization:WATCHMAN-TOKENheader on the request:curl -X GET -H "Authorization: WATCHMAN-TOKEN Token=\":token\"" http://127.0.0.1:8000/watchman/If you want to change the token name, you can set theWATCHMAN_TOKEN_NAME.
The value of this setting will be theGETparameter that you must pass in:WATCHMAN_TOKEN_NAME = 'custom-token-name'

GET http://127.0.0.1:8000/watchman/?custom-token-name=:tokenDEPRECATION WARNING:WATCHMAN_TOKENwas replaced by theWATCHMAN_TOKENSsetting to support multiple authentication tokens in django-watchman0.11.
It will continue to work until it’s removed in django-watchman1.0.Custom authentication/authorizationIf you want to protect the status endpoint with a customized
authentication/authorization decorator, you can addWATCHMAN_AUTH_DECORATORto your settings. This needs to be a dotted-path to a decorator, and defaults
towatchman.decorators.token_required:WATCHMAN_AUTH_DECORATOR = 'django.contrib.admin.views.decorators.staff_member_required'Note that thetoken_requireddecorator does not protect a view unlessWATCHMAN_TOKENSis set in settings.Custom checksdjango-watchman allows you to customize the checks which are run by modifying
theWATCHMAN_CHECKSsetting. Insettings.py:WATCHMAN_CHECKS = (
    'module.path.to.callable',
    'another.module.path.to.callable',
)You can also import the watchman.constants to include the DEFAULT_CHECKS and PAID_CHECKS in yoursettings.py:from watchman import constants as watchman_constants

WATCHMAN_CHECKS = watchman_constants.DEFAULT_CHECKS + ('module.path.to.callable', )Checks take no arguments, and must return adictwhose keys are applied to the JSON response. Use thewatchman.decorators.checkdecorator to capture exceptions:from watchman.decorators import check

@check
def my_check():
    return {'x': 1}In the absence of any checks, a 404 is thrown, which is then handled by thejson_viewdecorator.Run a subset of available checksA subset of checks may be run, by passing?check=module.path.to.callable&check=...in the request URL. Only the callables given in the querystring which are also
inWATCHMAN_CHECKSshould be run, eg:curl -XGET http://127.0.0.1:8080/watchman/?check=watchman.checks.cachesSkip specific checksYou can skip any number of checks, by passing?skip=module.path.to.callable&skip=...in the request URL. Only the checks inWATCHMAN_CHECKSwhich are not in the
querystring should be run, eg:curl -XGET http://127.0.0.1:8080/watchman/?skip=watchman.checks.emailCheck a subset of databases or cachesIf your application has a large number of databases or caches configured,
watchman may open too many connections as it checks each database or cache.You can set theWATCHMAN_DATABASESorWATCHMAN_CACHESsettings in order
to override the default set of databases and caches to be monitored.PingIf you want to simply check that your application is running and able to handle
requests, you can call ping:GEThttp://127.0.0.1:8000/watchman/ping/It will return the textpongwith a 200 status code. Calling this doesn’t
run any of the checks.Bare status viewIf you would like a “bare” status view (one that doesn’t report any details,
justHTTP 200if checks pass, andHTTP 500if any checks fail), you
can use thebare_statusview by putting the following intourls.py:import watchman.views
# ...
re_path(r'^status/?$', watchman.views.bare_status),Django management commandYou can also run your checks without starting the webserver and making requests.
This can be useful for testing your configuration before enabling a server,
checking configuration on worker servers, etc. Run the management command like so:python manage.py watchmanBy default, successful checks will not print any output. If all checks pass
successfully, the exit code will be0. If a check fails, the exit code will
be1, and the error message including stack trace will be printed tostderr.If you’d like to see output for successful checks as well, set verbosity to2or higher:python manage.py watchman -v 2
{"storage": {"ok": true}}
{"caches": [{"default": {"ok": true}}]}
{"databases": [{"default": {"ok": true}}]}If you’d like to run a subset of checks, use-cand a comma-separated list
of python module paths:python manage.py watchman -c watchman.checks.caches,watchman.checks.databases -v 2
{"caches": [{"default": {"ok": true}}]}
{"databases": [{"default": {"ok": true}}]}If you’d like to skip certain checks, use-sand a comma-separated list of
python module paths:python manage.py watchman -s watchman.checks.caches,watchman.checks.databases -v 2
{"storage": {"ok": true}}Use-hto see a full list of options:python manage.py watchman -hX-Watchman-Version response headerWatchman can return the version of watchman which is running to help you keep
track of whether or not your sites are using an up-to-date version. This is
disabled by default to prevent any unintended information leakage for websites
without authentication. To enable, update theEXPOSE_WATCHMAN_VERSIONsetting:EXPOSE_WATCHMAN_VERSION = TrueCustom response codeBy default, watchman will return a500HTTP response code, even if there’s a
failing check. You can specify a different response code for failing checks
using theWATCHMAN_ERROR_CODEsetting:WATCHMAN_ERROR_CODE = 200Loggingwatchman includes log messages using a logger calledwatchman.
You can configure this by configuring theLOGGINGsection of your Django
settings file.Here is a simple example that would log to the console:LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
        },
    },
    'loggers': {
        'watchman': {
            'handlers': ['console'],
            'level': 'DEBUG',
        },
    },
}More information is available in theDjango documentation.APM (Datadog, New Relic)If you’re using APM and watchman is being often hit for health checks (such as an ELB on
AWS), you will find some stats based on averages will be affected (average transaction
time, apdex, etc):You can disable APM instrumentation for watchman by using theWATCHMAN_DISABLE_APMsetting:WATCHMAN_DISABLE_APM = TrueThis currently supports the following agents:DatadogNew RelicPlease open an issue if there’s another APM you use which is being affected.Available checkscachesFor each cache indjango.conf.settings.CACHES:Set a test cache itemGet test itemDelete test itemdatabasesFor each database indjango.conf.settings.DATABASES:Verify connection by callingconnections[database].introspection.table_names()emailSend a test email toto@example.comusingdjango.core.mail.send_mail.If you’re using a 3rd party mail provider, this check could end up costing you
money, depending how aggressive you are with your monitoring. For this reason,
this check isnot enabledby default.For reference, if you were using Mandrill, and hitting your watchman endpoint
once per minute, this would cost you ~$5.60/month.Custom SettingsWATCHMAN_EMAIL_SENDER(default:watchman@example.com): Specify an email to be the sender of the test emailWATCHMAN_EMAIL_RECIPIENTS(default:[to@example.com]): Specify a list of email addresses to send the test emailWATCHMAN_EMAIL_HEADERS(default:{}): Specify a dict of custom headers to be added to the test emailstorageUsingdjango.core.files.storage.default_storage:Write a test fileCheck the test file’s sizeRead the test file’s contentsDelete the test fileBy default the test file gets written on the root of the djangoMEDIA_ROOT. If for whatever reasons this path is not writable by the user that runs the application you can override it by settingWATCHMAN_STORAGE_PATHto a specific path.
Remember that this must be within theMEDIA_ROOT, which by default is your project root. Insettings.py:WATCHMAN_STORAGE_PATH = "/path_to_your_app/foo/bar/"If theMEDIA_ROOTis already defined:from os.path import join as joinpath
WATCHMAN_STORAGE_PATH = joinpath(MEDIA_ROOT, "foo/bar")Default checksBy default, django-watchman will run checks against your databases
(watchman.checks.databases), caches (watchman.checks.caches), and
storage (watchman.checks.storage).Paid checksCurrently there is only one “paid” check -watchman.checks.email. You can
enable it by setting theWATCHMAN_ENABLE_PAID_CHECKStoTrue, or by
overriding theWATCHMAN_CHECKSsetting.Trying it out with DockerA sample project is available along with a Dockerfile to make it easy to try
out django-watchman.RequirementsDocker <https://www.docker.com/get-docker>InstructionsBuild and run the Docker image with the current local code:make runVisit watchman json endpoint in your browser:http://127.0.0.1:8000/watchman/Visit watchman dashboard in your browser:http://127.0.0.1:8000/watchman/dashboard/Visit watchman ping in your browser:http://127.0.0.1:8000/watchman/ping/Visit watchman bare status in your browser:http://127.0.0.1:8000/watchman/bare/HistoryUnreleased1.3.0 (2022-02-24)[#181] Update sample project to Django 4.x[#171] Improve database check performance: replace introspection.table_names() by a simple cursor query (@cristianemoyano)[#180,#174,] Switch testing to Github Actions from TravisCI, update to latest versions[#178] Add black, flake8, and isort linting1.2.0 (2020-09-20)[#163] Replaced deprecated url() calls with re_path() (@dominik-bln)1.1.1 (2020-05-04)[#159] Fixed invalid escape sequence in decorators by changing to a raw string1.1.0 (2020-03-16)[#154] Added custom path support for storage check1.0.1 (YYYY-MM-DD)Fix modal popups on dashboards when Type or Name fields contains spaces (@maikeps)1.0.0 (2019-12-18)Official django-watchman 1.0 release! Releases will (try to) follow semantic versioning from now on.Drop support for python 2 and Django<2 (@JBKahn)Drop usage ofdjango-jsonviewin favor of the Django’s built in JsonResponse (@JBKahn)0.18.0 (2019-08-19)[#142] Skip traces in Datadog ifWATCHMAN_DISABLE_APMis enabled (@robatwave)0.17.0 (2019-06-14)[#141] Disable APM monitoring onpingendpoint ifsettings.WATCHMAN_DISABLE_APMis configured (@JBKahn)0.16.0 (2019-03-19)[#131] Make watchman constants importable (@jonespm)[#134] Update Django/Python versions & clean up sample site Docker (@JayH5)0.15.0 (2018-02-27)[#114] Add “bare” status view (@jamesmallen)[#115] AddsWATCHMAN_DISABLE_APMoption (@xfxf)[#63] Disable watchman version output by default, addEXPOSE_WATCHMAN_VERSIONsetting (@mwarkentin)0.14.0 (2018-01-09)[#110] Replace vagrant + ansible with Dockerfile (@ryanwilsonperkin)[#111] Configure Django logging for checks (@dhoffman34)[#112] Add simple HTTP ping endpoint (@dhoffman34)0.13.1 (2017-05-27)[#101] Writebytesto dummy file on storage check to fix an issue in Python 3 (thanks @saily!)0.13.0 (2017-05-23)[#105] AddWATCHMAN_CACHESandWATCHMAN_DATABASESsettings to override the Django defaultsWhen using watchman with a large number of databases, the default checks can cause an excess of connections to the database / cacheNew settings allow you to check only a subset of databases / cachesWatchman will still default to checking all databases / caches, so no changes necessary for most apps0.12.0 (2017-02-22)[#100] AddWATCHMAN_EMAIL_SENDERsetting to customize email check “from” address0.11.1 (2017-02-14)[#99] Fix verbose output in management command on Django 1.8+0.11.0 (2016-08-02)Update tests to run on Django 1.7 - 1.10[#87] Fix 500 errors with ATOMIC_REQUESTS enabledDisables atomic transactions on the watchman views to prevent generic 500 errors[#88] Restructure dashboard and switch icon librariesMake check types singular on dashboardSwitch to FontAwesome instead of Glyphicon to track Bootstrap updatesImprove traceback display width[#92] Support multiple auth tokensFixes [#86]Deprecatessettings.WATCHMAN_TOKENand addssettings.WATCHMAN_TOKENS0.10.1 (2016-05-03)[#81] Fix header-based authentication for tokens w/ dashes (-)Regex was overly specific for header values (w)Added TODO to follow up with a full regex for valid characters according to the spec0.10.0 (2016-05-02)[#75] Enable header-based authenticationSet a header instead of passing the token via GET param:"Authorization:WATCHMAN-TOKENToken=\":token\""Improves security by keeping tokens out of logs[#79] Enable customization of email checkAddWATCHMAN_EMAIL_RECIPIENTSsetting - pass a list of recipients the email should be sent toAddWATCHMAN_EMAIL_HEADERSsetting - pass a dict of custom headers to be set on the email0.9.0 (2015-12-16)[#51] Update TravisCI Python / Django versions[#52] Fix deprecatedurl_patterns[#53] Change default error response code to500[#56] Add@checkdecorator and refactor existing checks to use it (thanks @benwebber!)[#57] Sortcaches/databasesin response for more consistent responses[#59] Add.editorconfigfor improved consistency in contributions[#61] AddVagrantfileand docs for how to run and develop on Vagrant instance[#65] Include assets in source tarball for Debian packaging (thanks @fladi)[#71] Unpindjango-jsonviewin setup.py[#72] Fix stacktrace on dashboard modal and increase width for better readability0.8.0 (2015-10-03)[#46] Allow custom response codes with theWATCHMAN_ERROR_CODEsetting0.7.1 (2015-08-14)Update headers inHISTORY.rstto attempt to fix localshop parsing issues0.7.0 (2015-08-14)[#40] Bumpdjango-jsonviewfor improved Django 1.8 compatibilityAlso brought travis Django test versions in line with currently supported Django versions (1.4.x, 1.7.x, 1.8.x)0.6.0 (2015-07-02)[#30] Allow users to specify a custom authentication/authorization decoratorOverride the@authdecorator by settingWATCHMAN_AUTH_DECORATORto a dot-separated path to your own decoratoreg.WATCHMAN_AUTH_DECORATOR = 'django.contrib.admin.views.decorators.staff_member_required'Token-based authentication remains the default[#31], [#34] Add a human-friendly status dashboardAvailable at<watchmanurl>/dashboard/?check&?skipGET params work on the dashboard as well[#35] AddX-Watchman-Versionheader to responses0.5.0 (2015-01-25)Addwatchmanmanagement commandExit code of0if all checks pass,1otherwisePrint json stacktrace tostderrif check failsHandles--verbosityoption to print all status checks-c,--checks,-s,--skipsoptions take comma-separated list of python paths to run / skipImprove identifiability of emails sent from a django-watchman endpointFrom:watchman@example.comSubject: django-watchman email checkBody: This is an automated test of the email system.AddX-DJANGO-WATCHMAN:Truecustom headerAdd new default check:storagecheckChecks that files can be both written and read with the current Django storage engineAddWATCHMAN_ENABLE_PAID_CHECKSsetting to enable all paid checks without modifyingWATCHMAN_CHECKSRemoveemail_statusfrom default checksRefactorutils.get_checksto allow reuse in management commandget_checksnow performs the optional check inclusion / skippingstatusrefactored to pullcheck_list/skip_listfrom GET params and pass them toget_checksNamespace cache keysUpdate documentation0.4.0 (2014-09-08)Add the ability to skip certain checks by passing one or moreskip=path.to.callableGET params when hitting the watchman URL0.3.0 (2014-09-05)New check - email (watchman.checks.email_status)! django-watchman will now
check that your email settings are working too!Fix a few small issues in the readmeRearrange some of the code in checks.py0.2.2 (2014-09-05)Fix and run tests on Python 2.7 and 3.4Bump django-jsonview dependency to latestUpdate tox envlist and travis config to test 2.7 / 3.40.2.1 (2014-09-04)Initialize django during tests to prevent app loading issue for Django >= 1.7SuppressMIDDLEWARE_CLASSESwarning for Django >= 1.7Reorganize test importsFixmake test,make coverage,make releasecommandsAdd htmlcov/ directory to .gitignoreTest django 1.4, 1.6, 1.70.2.0 (2014-09-04)Custom checks can now be written and run using theWATCHMAN_CHECKSsettingA subset of the available checks can be run by passing thecheckGET param
when hitting the watchman url0.1.2 (2014-02-21)Move package requirements out of requirements.txt and into setup.py0.1.1 (2014-02-09)Removedjango>=1.5.5version specificationRemovewheelrequirement0.1.0 (2014-02-08)First release on PyPI.