Package: cronitor
Cronitor Python LibraryCronitorprovides end-to-end monitoring for background jobs, websites, APIs, and anything else that can send or receive an HTTP request. This library provides convenient access to the Cronitor API from applications written in Python. See ourAPI docsfor detailed references on configuring monitors and sending telemetry pings.In this guide:InstallationMonitoring Background JobsSending Telemetry EventsConfiguring MonitorsPackage Configuration & Env VarsCommand Line UsageInstallationpip install cronitorMonitoring Background JobsCelery Auto-Discovercronitor-pythoncan automatically discover all of your declared Celery tasks, including your Celerybeat scheduled tasks,
creating monitors for them and sending pings when tasks run, succeed, or fail. Your API keys can be foundhere.Requires Celery 4.0 or higher. Celery auto-discover utilizes the Celerymessage protocol version 2.Some important notes on supportTasks onsolar schedulesare not supported and will be ignored.django-celery-beatis not yet supported, but is in the works.If you use the defaultPersistentScheduler, the celerybeat integration overrides the celerybeat local task run database (as referencedherein the docs), namedcelerybeat-scheduleby default. If you currently specify a custom location for this database, this integration will override it.Veryfew people require setting custom locations for this database. If you fall into this group and want to usecronitor-python's celerybeat integration, please reach out to Cronitor support.importcronitor.celeryfromceleryimportCeleryapp=Celery()app.conf.beat_schedule={'run-me-every-minute':{'task':'tasks.every_minute_celery_task','schedule':60}}# Discover all of your celery tasks and automatically add monitoring.cronitor.celery.initialize(app,api_key="apiKey123")@app.taskdefevery_minute_celery_task():print("running a background job with celery...")@app.taskdefnon_scheduled_celery_task():print("Even though I'm not on a schedule, I'll still be monitored!")If you want only to monitor Celerybeat periodic tasks, and not tasks triggered any other way, you can setcelereybeat_only=Truewhen initializing:app=Celery()cronitor.celery.initialize(app,api_key="apiKey123",celerybeat_only=True)Manual IntegrationThe@cronitor.jobis a lightweight way to monitor any background task regardless of how it is executed. It will send telemetry events before calling your function and after it exits. If your function raises an exception afailevent will be sent (and the exception re-raised).importcronitor# your api keys can found here - https://cronitor.io/settings/apicronitor.api_key='apiKey123'# Apply the cronitor decorator to monitor any function.# If no monitor matches the provided key, one will be created automatically.@cronitor.job('send-invoices')defsend_invoices_task(*args,**kwargs):...Sending Telemetry EventsIf you want to send a heartbeat events, or want finer control over when/howtelemetry eventsare sent for your jobs, you can create a monitor instance and call the.pingmethod.importcronitor# your api keys can found here - https://cronitor.io/settings/apicronitor.api_key='apiKey123'# optionally, set an environmentcronitor.environment='staging'monitor=cronitor.Monitor('heartbeat-monitor')monitor.ping()# send a heartbeat event# optional params can be passed as keyword arguements.# for a complete list see https://cronitor.io/docs/telemetry-api#parametersmonitor.ping(state='run|complete|fail|ok',# run|complete|fail used to measure lifecycle of a job, ok used for manual reset only.message='',# message that will be displayed in alerts as well as monitor activity panel on your dashboard.metrics={'duration':100,# how long the job ran (complete|fail only). cronitor will calculate this when not provided'count':4500,# if your job is processing a number of items you can report a count'error_count':10# the number of errors that occurred while this job was running})Configuring MonitorsYou can configure all of your monitors using a single YAML file. This can be version controlled and synced to Cronitor as part of
a deployment or build process. For details on all of the attributes that can be set, see theMonitor APIdocumentation.importcronitor# your api keys can found here - https://cronitor.io/settings/apicronitor.api_key='apiKey123'cronitor.read_config('./cronitor.yaml')# parse the yaml file of monitorscronitor.validate_config()# send monitors to Cronitor for configuration validationcronitor.apply_config()# sync the monitors from the config file to Cronitorcronitor.generate_config()# generate a new config file from the Cronitor APIThe timeout value for validate_config, apply_config and generate_config is 10 seconds by default. The value can be rewritten by setting the environment variableCRONITOR_TIMEOUT. It can also be rewritten by assigning a value to cronitor.timeout.importcronitorcronitor.timeout=30cronitor.apply_config()Thecronitor.yamlfile includes three top level keysjobs,checks,heartbeats. You can configure monitors under each key by definingmonitors.jobs:nightly-database-backup:schedule:0 0 * * *notify:-devops-alert-pagerdutyassertions:-metric.duration < 5 minutessend-welcome-email:schedule:every 10 minutesassertions:-metric.count > 0-metric.duration < 30 secondschecks:cronitor-homepage:request:url:https://cronitor.ioregions:-us-east-1-eu-central-1-ap-northeast-1assertions:-response.code = 200-response.time < 2scronitor-ping-api:request:url:https://cronitor.link/pingassertions:-response.body contains ok-response.time < .25sheartbeats:production-deploy:notify:alerts:['deploys-slack']events:true# send alert when the event occursYou can also create and update monitors by callingMonitor.put. For details on all of the attributes that can be set see the Monitor API [documentation)(https://cronitor.io/docs/monitor-api#attributes).importcronitormonitors=cronitor.Monitor.put([{'type':'job','key':'send-customer-invoices','schedule':'0 0 * * *','assertions':['metric.duration < 5 min'],'notify':['devops-alerts-slack']},{'type':'check','key':'Cronitor Homepage','schedule':'every 45 seconds','request':{'url':'https://cronitor.io'},'assertions':['response.code = 200','response.time < 600ms',]}])Pausing, Reseting, and Deletingimportcronitormonitor=cronitor.Monitor('heartbeat-monitor');monitor.pause(24)# pause alerting for 24 hoursmonitor.unpause()# alias for .pause(0)monitor.ok()# manually reset to a passing state alias for monitor.ping({state: ok})monitor.delete()# destroy the monitorPackage ConfigurationThe package needs to be configured with your account'sAPI key, which is available on theaccount settingspage. You can also optionally specify anapi_versionand anenvironment. If not provided, your account default is used. These can also be supplied using the environment variablesCRONITOR_API_KEY,CRONITOR_API_VERSION,CRONITOR_ENVIRONMENT.importcronitor# your api keys can found here - https://cronitor.io/settingscronitor.api_key='apiKey123'cronitor.api_version='2020-10-01'cronitor.environment='cluster_1_prod'Command Line Usage>>python-mcronitor-h

usage:cronitor[-h][--apikeyAPIKEY][--keyKEY][--msgMSG](--run|--complete|--fail|--ok|--pausePAUSE)SendstatusmessagestoCronitorpingAPI.

optionalarguments:-h,--helpshowthishelpmessageandexit--authkeyAUTHKEY,-aAUTHKEYAuthKeyfromAccountpage--keyKEY,-kKEYUniquekeyforthemonitortotakeping--msgMSG,-mMSGOptionalmessagetosendwithping/fail--tick,-tCallpingongivenmonitor--run,-rCallpingwithstate=runongivenmonitor--complete,-CCallpingwithstate=completeongivenmonitor--fail,-fCallpingwithstate=failongivenmonitor--pausePAUSE,-PPAUSECallpauseongivenmonitorContributingPull requests and features are happily considered! By participating in this project you agree to abide by theCode of Conduct.To contributeFork, then clone the repo:git clone git@github.com:your-username/cronitor-python.gitSet up your machine:pip install -r requirementsMake sure the tests pass:pytestMake your change. Add tests for your change. Make the tests pass:pytestPush to your fork andsubmit a pull request