Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
1f1eb0e
Add envelope encoding and background transport
claude Oct 29, 2026
281aa05
Add capture_exception, capture_message and cronitor.logger
claude Oct 29, 2026
b6de094
Capture exceptions raised inside @cronitor.job
claude Oct 29, 2026
c9f14ca
Add cronitor.LogHandler for the logging module
claude Oct 29, 2026
cdc5626
Test the default HTTP send path against a loopback server
claude Oct 29, 2026
20fa49f
Document exceptions and logs, bump version to 5.0.0
claude Oct 29, 2026
05f5f0f
Send strict JSON and report a missing API key once
claude Oct 29, 2026
a7167b8
Add cronitor.app to bind events and logs to an app monitor
claude Oct 29, 2026
6c0270f
Rename the app binding to service
claude Oct 29, 2026
f32175e
Keep running the job when a ping fails, and fix the README DSN
claude Oct 29, 2026
31e7622
Restore the success-path assertions in the job decorator tests
claude Oct 29, 2026
18410f1
Drop the parent's HTTP session in a forked child
claude Oct 29, 2026
4809349
Keep stdlib logger calls working on cronitor.logger
claude Oct 29, 2026
46e474f
Trim exception events to stay under the server's size limit
claude Oct 29, 2026
a7ea2f8
Cap log attributes like the server and default LogHandler to INFO
claude Oct 29, 2026
8626a35
Drop envelopes while rate limited instead of sleeping the sender
claude Oct 29, 2026
3f886a8
Note in the README that threads do not inherit the job binding
claude Oct 29, 2026
3a96477
Ignore non-integer status codes from transport stubs
claude Oct 29, 2026
d7d69ba
Merge remote-tracking branch 'origin/master' into claude/sentry-excep…
aflanagan Nov 27, 2026
045f0eb
Align error tracking with Error App DSNs and the Errors API
aflanagan Nov 27, 2026
9d073b6
Fix errors monitor YAML window example and clarify ingest_url
aflanagan Nov 27, 2026
3c5ec1b
Post error envelopes to /e using ingest_key
aflanagan Nov 29, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
126 changes: 123 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,10 @@

In this guide:

- [Installation](#Installation)
- [Installation](#installation)
- [Monitoring Background Jobs](#monitoring-background-jobs)
- [Sending Telemetry Events](#sending-telemetry-events)
- [Error Tracking](#error-tracking)
- [Configuring Monitors](#configuring-monitors)
- [Package Configuration & Env Vars](#package-configuration)
- [Command Line Usage](#command-line-usage)
Expand Down Expand Up @@ -124,6 +125,98 @@ monitor.ping(
)
```

## Error Tracking

Cronitor captures exceptions and messages natively with no extra dependency and sends them from a background thread, so your application is never slowed down or interrupted by the network: requests time out after 5 seconds, failures are logged as warnings, and nothing is ever raised to your code.

Configure `cronitor.ingest_key` using the ingest key from an Error App created in the Cronitor dashboard or via `cronitor.ErrorApp.create(...)`. `cronitor.ingest_url` is optional and defaults to `https://cronitor.link`. Envelopes are posted to `/e`:

```python
import cronitor

cronitor.ingest_key = '<ingest_key>'
# cronitor.ingest_url = 'https://cronitor.link' # optional
cronitor.environment = 'production' # optional, or CRONITOR_ENVIRONMENT
cronitor.release = '2.4.1' # optional, or CRONITOR_RELEASE
```

#### Capturing exceptions and messages

```python
try:
import_orders()
except Exception as e:
cronitor.capture_exception(
e,
monitor='import-orders',
level='error',
tags={'region': 'us-east-1'},
extra={'batch': 42},
fingerprint=['import-orders', 'timeout'],
)

cronitor.capture_message(
'Disk 90% full',
level='warning',
tags={'host': 'worker-1'},
extra={'mount': '/var'},
fingerprint='disk-space-warning',
)

# bound to a monitor and its environment
monitor = cronitor.Monitor('import-orders')
monitor.capture_exception() # inside an except block, defaults to the current exception
monitor.capture_message('Import finished with warnings', level='warning')
```

`capture_exception` and `capture_message` return the event id, or `None` if nothing was sent (for example when `cronitor.ingest_key` is not configured). Events include the exception chain (`raise ... from ...`), stack frames with five lines of source context, the hostname, release, and environment. Local variables are never sent. `fingerprint` accepts a string or a list of strings for custom grouping; omit it to use Cronitor's default grouping.

Queued events are flushed automatically when the process exits. Call `cronitor.flush(timeout=2.0)` to flush earlier, for example at the end of a serverless handler.

#### Exceptions inside `@cronitor.job`

When a function decorated with `@cronitor.job` raises, the `fail` ping is sent first (best effort) and an unhandled exception event with the full stack trace follows, bound to the same monitor and run series.

Auto-capture defaults to `True`. Turn it off globally or per job:

```python
cronitor.capture_exceptions = False

@cronitor.job('import-orders', capture_exceptions=False)
def import_orders():
...
```

Exceptions and messages captured while a `@cronitor.job` runs are bound to that monitor and run automatically via a `ContextVar`. Threads started inside a job do not inherit this binding, so pass `monitor=` and `series=` explicitly to captures made from worker threads (`cronitor.capture.current_job()` returns the active binding).

#### Managing Error Apps and Error Groups

Use `cronitor.ErrorApp` and `cronitor.ErrorGroup` with your REST API key (`cronitor.api_key`):

```python
import cronitor

cronitor.api_key = 'apiKey123'

# Create and manage Error Apps
app = cronitor.ErrorApp.create(name='Billing API')
print(app.key, app.ingest_key, app.ingest_url)

apps = cronitor.ErrorApp.list(page=1, pageSize=50)
app.update(name='Payments API')
app.rotate_key() # refreshes app.ingest_key; the old key stops working immediately
app.delete()

# Query and triage Error Groups
groups = cronitor.ErrorGroup.list(app='app_0123456789abcdef', status='open', env='production')
group = cronitor.ErrorGroup('err_0123456789abcdef')
print(group.data.title)
group.update(status='resolved', env='production')

events = group.events(env='production', limit=25)
event = group.event(events['data'][0]['event_id'])
```

## Configuring Monitors

### YAML Configuration File
Expand Down Expand Up @@ -155,7 +248,7 @@ cronitor.timeout = 30
cronitor.apply_config()
```

The `cronitor.yaml` file includes three top level keys `jobs`, `checks`, `heartbeats`. You can configure monitors under each key by defining [monitors](https://cronitor.io/docs/monitor-api#attributes).
The `cronitor.yaml` file supports four top level keys: `jobs`, `checks`, `heartbeats`, and `errors`. You can configure monitors under each key by defining [monitors](https://cronitor.io/docs/monitor-api#attributes).

```yaml
jobs:
Expand Down Expand Up @@ -197,6 +290,17 @@ heartbeats:
alerts: ['deploys-slack']
events: true # send alert when the event occurs

errors:
billing-error-spikes:
trigger: spike
apps:
- app_0123456789abcdef
threshold: 25
window: 5m
per: fingerprint
notify:
- devops-alert-pagerduty

```
#### Async Uploads
If you are working with large YAML files (300+ monitors), you may hit timeouts when trying to sync monitors in a single http request. This workload to be processed asynchronously by adding the key `async: true` to the config file. The request will immediately return a `batch_key`. If a `webhook_url` parameter is included, Cronitor will POST to that URL with the results of the background processing and will include the `batch_key` matching the one returned in the initial response.
Expand Down Expand Up @@ -229,6 +333,13 @@ monitors = cronitor.Monitor.put([
'response.code = 200',
'response.time < 600ms',
]
},
{
'type': 'errors',
'key': 'new-billing-errors',
'trigger': 'new',
'apps': ['app_0123456789abcdef'],
'notify': ['devops-alerts-slack']
}
])
```
Expand Down Expand Up @@ -297,7 +408,14 @@ monitor.delete() # destroy the monitor

## Package Configuration

The package needs to be configured with your account's `API key`, which is available on the [account settings](https://cronitor.io/settings) page. You can also optionally specify an `api_version` and an `environment`. If not provided, your account default is used. These can also be supplied using the environment variables `CRONITOR_API_KEY`, `CRONITOR_API_VERSION`, `CRONITOR_ENVIRONMENT`.
The package needs to be configured with your account's `API key` (for pings and the REST API), which is available on the [account settings](https://cronitor.io/settings) page. You can also optionally specify an `api_version` and an `environment`. If not provided, your account default is used. These can also be supplied using the environment variables `CRONITOR_API_KEY`, `CRONITOR_API_VERSION`, `CRONITOR_ENVIRONMENT`.

Additional settings:

- `cronitor.ingest_key`: Error App ingest key used to capture exceptions and messages.
- `cronitor.release` (`CRONITOR_RELEASE`): Release string attached to captured events.
- `cronitor.ingest_url` (`CRONITOR_INGEST_URL`): Host for telemetry pings and error envelopes (default `https://cronitor.link`), e.g. `http://localhost:9100` in development. Envelopes are posted to `/e` on this host.
- `cronitor.capture_exceptions`: Module default for `@cronitor.job` auto-capture (default `True`).

```python
import cronitor
Expand All @@ -306,6 +424,8 @@ import cronitor
cronitor.api_key = 'apiKey123'
cronitor.api_version = '2020-10-01'
cronitor.environment = 'cluster_1_prod'
cronitor.ingest_key = '<ingest_key>'
cronitor.release = '2.4.1'
```

## Command Line Usage
Expand Down
45 changes: 39 additions & 6 deletions cronitor/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@
import threading

from .monitor import Monitor, YAML
from .errors import ErrorApp, ErrorGroup
from . import capture, ingest
from .ingest import flush
from .capture import capture_exception, capture_message

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
Expand All @@ -23,6 +27,12 @@
if timeout is not None:
timeout = int(timeout)

dsn = os.getenv('CRONITOR_DSN', None)
ingest_key = None
ingest_url = os.getenv('CRONITOR_INGEST_URL') or ingest.DEFAULT_INGEST_URL
release = os.getenv('CRONITOR_RELEASE', None)
capture_exceptions = True

celerybeat_only = False

# monitor attributes can be synced at process startup
Expand All @@ -36,6 +46,12 @@
class MonitorNotFound(Exception):
pass

class ErrorAppNotFound(Exception):
pass

class ErrorGroupNotFound(Exception):
pass

class ConfigValidationError(Exception):
pass

Expand All @@ -54,8 +70,16 @@ class State(object):
COMPLETE = 'complete'
FAIL = 'fail'

# include_output is deprecated in favor of log_output and can be removed in 5.0 release
def job(key, env=None, log_output=True, include_output=True, attributes=None):
def _safe_ping(monitor, **params):
"""Pings are best effort: a telemetry outage must never stop or fail the job."""
try:
return monitor.ping(**params)
except Exception as e:
logger.warning('Cronitor could not send the %s ping for %s: %s', params.get('state'), monitor.key, e)
return None


def job(key, env=None, log_output=True, include_output=True, attributes=None, capture_exceptions=None):

if type(attributes) is dict:
attributes['key'] = key
Expand All @@ -68,17 +92,25 @@ def wrapped(*args, **kwargs):

monitor = Monitor(key, env=env)
# use start as the series param to match run/fail/complete correctly
monitor.ping(state=State.RUN, series=start)
_safe_ping(monitor, state=State.RUN, series=start)
job_env = env or this.environment
token = capture.bind_job(key, start, job_env)
try:
out = func(*args, **kwargs)
except Exception as e:
duration = datetime.now().timestamp() - start
monitor.ping(state=State.FAIL, message=str(e), metrics={'duration': duration}, series=start)
_safe_ping(monitor, state=State.FAIL, message=str(e), metrics={'duration': duration}, series=start)
should_capture = this.capture_exceptions if capture_exceptions is None else capture_exceptions
if should_capture:
capture._capture_exception(e, monitor=key, series=start, env=job_env,
mechanism='cronitor.job', handled=False)
raise e
finally:
capture.unbind_job(token)

duration = datetime.now().timestamp() - start
message = str(out) if all([log_output, include_output]) else None
monitor.ping(state=State.COMPLETE, message=message, metrics={'duration': duration}, series=start)
_safe_ping(monitor, state=State.COMPLETE, message=message, metrics={'duration': duration}, series=start)
return out

return wrapped
Expand All @@ -102,7 +134,8 @@ def apply_config(rollback=False):
job_count = len(monitors.get('jobs', []))
check_count = len(monitors.get('checks', []))
heartbeat_count = len(monitors.get('heartbeats', []))
total_count = sum([job_count, check_count, heartbeat_count])
error_count = len(monitors.get('errors', []))
total_count = sum([job_count, check_count, heartbeat_count, error_count])
logger.info('{} monitor{} {}'.format(total_count, 's' if total_count != 1 else '', 'validated.' if rollback else 'synced.',))
return True
except (yaml.YAMLError, ConfigValidationError, APIValidationError, APIError, AuthenticationError) as e:
Expand Down
1 change: 1 addition & 0 deletions cronitor/_version.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
__version__ = '4.10.0'
Loading