From 1f1eb0e768b878bdddf35cda0b801453b08dd868 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 29 Oct 2026 20:56:06 +0000 Subject: [PATCH 01/18] Add envelope encoding and background transport cronitor/ingest.py builds Sentry-format envelopes and sends them to {ingest_url}/api/envelope from one daemon thread with a bounded queue. Events go out one envelope each; log records batch to 100 or 5 seconds. Bodies are gzipped, sends time out after 5 seconds with one retry, a 429 pauses sending for Retry-After (capped at 60 seconds), and failures are logged, never raised. The worker starts lazily, restarts after fork, and queued items are flushed at exit with a 2 second cap. cronitor.ingest_url (env CRONITOR_INGEST_URL, default https://cronitor.link) now also sets the ping URL base, so a dev stack can receive everything. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01B4Z4DjN96ccpNoVRZuoCxo --- cronitor/__init__.py | 5 + cronitor/_version.py | 1 + cronitor/ingest.py | 340 ++++++++++++++++++++++++++++++ cronitor/monitor.py | 3 +- cronitor/tests/envelope_parser.py | 104 +++++++++ cronitor/tests/test_ingest.py | 327 ++++++++++++++++++++++++++++ 6 files changed, 779 insertions(+), 1 deletion(-) create mode 100644 cronitor/_version.py create mode 100644 cronitor/ingest.py create mode 100644 cronitor/tests/envelope_parser.py create mode 100644 cronitor/tests/test_ingest.py diff --git a/cronitor/__init__.py b/cronitor/__init__.py index e48dceb..d701c42 100644 --- a/cronitor/__init__.py +++ b/cronitor/__init__.py @@ -10,6 +10,8 @@ import threading from .monitor import Monitor, YAML +from . import ingest +from .ingest import flush logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) @@ -23,6 +25,9 @@ if timeout is not None: timeout = int(timeout) +# base URL for telemetry pings and exception/log envelopes, e.g. http://localhost:9100 in development +ingest_url = os.getenv('CRONITOR_INGEST_URL') or ingest.DEFAULT_INGEST_URL + celerybeat_only = False # monitor attributes can be synced at process startup diff --git a/cronitor/_version.py b/cronitor/_version.py new file mode 100644 index 0000000..3161916 --- /dev/null +++ b/cronitor/_version.py @@ -0,0 +1 @@ +__version__ = '4.9.0' diff --git a/cronitor/ingest.py b/cronitor/ingest.py new file mode 100644 index 0000000..d726a3f --- /dev/null +++ b/cronitor/ingest.py @@ -0,0 +1,340 @@ +"""Envelope encoding and background transport for exception events and logs. + +Payloads use the Sentry envelope format and are sent to +``{cronitor.ingest_url}/api/envelope``. Sending happens on one daemon thread +with a bounded queue, so callers are never blocked by the network and never +see a transport error. +""" +import atexit +import gzip +import json +import logging +import os +import queue +import threading +import time +from datetime import datetime, timezone + +import cronitor +from ._version import __version__ + +logger = logging.getLogger(__name__) + +DEFAULT_INGEST_URL = 'https://cronitor.link' +SDK_NAME = 'cronitor-python' +SDK_VERSION = __version__ + +MAX_QUEUE_SIZE = 1000 +LOG_BATCH_SIZE = 100 +LOG_BATCH_INTERVAL = 5.0 +SEND_TIMEOUT = 5 +SEND_RETRIES = 1 +MAX_RETRY_AFTER = 60.0 +ATEXIT_FLUSH_TIMEOUT = 2.0 + +EVENT_CONTENT_TYPE = 'application/json' +LOG_CONTENT_TYPE = 'application/vnd.sentry.items.log+json' + +_worker_state = threading.local() +_start_lock = threading.Lock() + + +def _reset_after_fork(): + # a lock held by another thread at fork time stays locked forever in the child + global _start_lock + _start_lock = threading.Lock() + + +if hasattr(os, 'register_at_fork'): + os.register_at_fork(after_in_child=_reset_after_fork) + + +def base_url(): + """The scheme and host that pings and envelopes are sent to, without a trailing slash.""" + return (cronitor.ingest_url or DEFAULT_INGEST_URL).rstrip('/') + + +def envelope_url(): + return '{}/api/envelope'.format(base_url()) + + +def sdk_info(): + return {'name': SDK_NAME, 'version': SDK_VERSION} + + +def auth_header(api_key): + return 'Sentry sentry_key={}, sentry_version=7, sentry_client={}/{}'.format(api_key, SDK_NAME, SDK_VERSION) + + +def request_headers(api_key): + return { + 'Content-Type': 'application/x-sentry-envelope', + 'Content-Encoding': 'gzip', + 'User-Agent': 'cronitor-python', + 'X-Sentry-Auth': auth_header(api_key), + } + + +def format_timestamp(value=None): + """RFC 3339 in UTC with microseconds and a Z suffix.""" + value = value or datetime.now(timezone.utc) + if value.tzinfo is not None: + value = value.astimezone(timezone.utc) + return value.strftime('%Y-%m-%dT%H:%M:%S.%fZ') + + +def _json_default(value): + try: + return repr(value) + except Exception: + return '' % type(value).__name__ + + +def json_bytes(obj): + return json.dumps(obj, default=_json_default, ensure_ascii=False, separators=(',', ':')).encode('utf-8') + + +def serialize_envelope(headers, items): + """Build envelope bytes from a header dict and (item_header, payload_bytes) pairs. + + Every item header gets a ``length`` equal to the payload's byte length. + """ + parts = [json_bytes(headers), b'\n'] + for item_headers, payload in items: + item_headers = dict(item_headers, length=len(payload)) + parts.extend([json_bytes(item_headers), b'\n', payload, b'\n']) + return b''.join(parts) + + +def event_envelope(payload, event_id, sent_at=None): + headers = {'event_id': event_id, 'sent_at': format_timestamp(sent_at), 'sdk': sdk_info()} + item = {'type': 'event', 'content_type': EVENT_CONTENT_TYPE} + return serialize_envelope(headers, [(item, payload)]) + + +def log_envelope(records, sent_at=None): + headers = {'sent_at': format_timestamp(sent_at), 'sdk': sdk_info()} + item = {'type': 'log', 'item_count': len(records), 'content_type': LOG_CONTENT_TYPE} + return serialize_envelope(headers, [(item, json_bytes({'items': records}))]) + + +def in_worker_thread(): + """True on the transport thread, so log handlers can ignore records the transport itself causes.""" + return getattr(_worker_state, 'active', False) + + +def _retry_after(response): + headers = getattr(response, 'headers', None) or {} + delay = None + try: + delay = float(headers.get('Retry-After')) + except (TypeError, ValueError): + limits = headers.get('X-Sentry-Rate-Limits') + if limits: + try: + delay = float(limits.split(',')[0].split(':')[0]) + except ValueError: + delay = None + if delay is None: + delay = MAX_RETRY_AFTER + return max(0.0, min(delay, MAX_RETRY_AFTER)) + + +class Transport(object): + """Sends envelopes from a single daemon thread. + + ``send(url, data, headers, timeout)`` performs the HTTP request and returns a + response with ``status_code`` and ``headers``; it is injectable for tests. + """ + + def __init__(self, send=None, sleep=None, maxsize=MAX_QUEUE_SIZE, + batch_size=LOG_BATCH_SIZE, batch_interval=LOG_BATCH_INTERVAL): + self._send = send or self._http_send + self._sleep = sleep or time.sleep + self._maxsize = maxsize + self._batch_size = batch_size + self._batch_interval = batch_interval + self._session = None + self._queue = None + self._thread = None + self._pid = None + self._rate_limited_until = 0.0 + self.dropped = 0 + + # caller side + + def submit_event(self, event, api_key=None): + """Queue one event dict. Returns False when it was not queued.""" + api_key = self._api_key(api_key) + if not api_key: + return False + return self._put(('event', envelope_url(), api_key, event['event_id'], json_bytes(event))) + + def submit_log(self, record, api_key=None): + """Queue one log record dict. Returns False when it was not queued.""" + api_key = self._api_key(api_key) + if not api_key: + return False + return self._put(('log', envelope_url(), api_key, record)) + + def flush(self, timeout=2.0): + """Wait up to ``timeout`` seconds for queued items, including buffered logs, to be sent.""" + if self._thread is None or self._pid != os.getpid() or not self._thread.is_alive(): + return True + deadline = time.monotonic() + timeout + done = threading.Event() + try: + self._queue.put(('flush', done), timeout=timeout) + except queue.Full: + return False + return done.wait(max(0.0, deadline - time.monotonic())) + + def _api_key(self, api_key): + api_key = api_key or cronitor.api_key + if not api_key: + logger.error('No API key detected. Set cronitor.api_key to send exceptions and logs.') + return api_key + + def _put(self, item): + try: + self._ensure_worker() + self._queue.put_nowait(item) + return True + except queue.Full: + self.dropped += 1 + if self.dropped == 1 or self.dropped % 1000 == 0: + logger.warning('Cronitor ingest queue is full, %d item(s) dropped so far.', self.dropped) + return False + except Exception as e: + logger.warning('Cronitor could not queue an item: %s', e) + return False + + def _ensure_worker(self): + pid = os.getpid() + if self._pid == pid and self._thread is not None and self._thread.is_alive(): + return + with _start_lock: + if self._pid == pid and self._thread is not None and self._thread.is_alive(): + return + if self._pid != pid or self._queue is None: + # first use, or a forked child: items queued by the parent are not ours to send + self._queue = queue.Queue(maxsize=self._maxsize) + thread = threading.Thread(target=self._run, args=(self._queue,), name='cronitor-ingest') + thread.daemon = True + thread.start() + self._thread = thread + self._pid = pid + _register_atexit() + + # worker side + + def _run(self, q): + _worker_state.active = True + buffers = {} + deadline = None + while True: + timeout = None if deadline is None else max(0.0, deadline - time.monotonic()) + try: + item = q.get(timeout=timeout) + except queue.Empty: + self._flush_logs(buffers) + deadline = None + continue + try: + kind = item[0] + if kind == 'event': + _, url, api_key, event_id, payload = item + self._deliver(url, api_key, event_envelope(payload, event_id)) + elif kind == 'log': + _, url, api_key, record = item + batch = buffers.setdefault((url, api_key), []) + batch.append(record) + if deadline is None: + deadline = time.monotonic() + self._batch_interval + if len(batch) >= self._batch_size: + del buffers[(url, api_key)] + self._deliver(url, api_key, log_envelope(batch)) + if not buffers: + deadline = None + elif kind == 'flush': + self._flush_logs(buffers) + deadline = None + item[1].set() + except Exception as e: + logger.warning('Cronitor could not send an envelope: %s', e) + finally: + q.task_done() + + def _flush_logs(self, buffers): + while buffers: + (url, api_key), batch = buffers.popitem() + try: + self._deliver(url, api_key, log_envelope(batch)) + except Exception as e: + logger.warning('Cronitor could not send logs: %s', e) + + def _deliver(self, url, api_key, body): + wait = self._rate_limited_until - time.monotonic() + if wait > 0: + self._sleep(wait) + try: + response = self._send(url, gzip.compress(body, 6), request_headers(api_key), SEND_TIMEOUT) + except Exception as e: + logger.warning('Cronitor could not send an envelope to %s: %s', url, e) + return + status = getattr(response, 'status_code', None) + if status == 429: + delay = _retry_after(response) + self._rate_limited_until = time.monotonic() + delay + logger.warning('Cronitor rate limited the envelope; pausing sends for %.0f seconds.', delay) + elif status is not None and status >= 400: + logger.warning('Cronitor rejected an envelope with HTTP %s.', status) + + def _http_send(self, url, data, headers, timeout): + if self._session is None: + from .monitor import retry_session + self._session = retry_session(retries=SEND_RETRIES) + return self._session.post(url, data=data, headers=headers, timeout=timeout) + + +_transport = Transport() +_atexit_registered = False + + +def get_transport(): + return _transport + + +def set_transport(transport): + """Replace the module transport (for tests or a custom ``send``). Returns the previous one.""" + global _transport + previous, _transport = _transport, transport + return previous + + +def submit_event(event, api_key=None): + return _transport.submit_event(event, api_key=api_key) + + +def submit_log(record, api_key=None): + return _transport.submit_log(record, api_key=api_key) + + +def flush(timeout=2.0): + """Block up to ``timeout`` seconds while queued events and logs are sent.""" + try: + return _transport.flush(timeout) + except Exception as e: + logger.warning('Cronitor flush failed: %s', e) + return False + + +def _flush_at_exit(): + flush(ATEXIT_FLUSH_TIMEOUT) + + +def _register_atexit(): + global _atexit_registered + if not _atexit_registered: + _atexit_registered = True + atexit.register(_flush_at_exit) diff --git a/cronitor/monitor.py b/cronitor/monitor.py index 657c79d..b3902ef 100644 --- a/cronitor/monitor.py +++ b/cronitor/monitor.py @@ -8,6 +8,7 @@ import cronitor +from .ingest import base_url from urllib3.util.retry import Retry from requests.adapters import HTTPAdapter @@ -207,7 +208,7 @@ def _clean_params(self, params): } def _ping_api_url(self): - return "https://cronitor.link/p/{}/{}".format(self.api_key, self.key) + return "{}/p/{}/{}".format(base_url(), self.api_key, self.key) @classmethod def list(cls, keys=None, page=1, pageSize=100, auto_paginate=False, **filters): diff --git a/cronitor/tests/envelope_parser.py b/cronitor/tests/envelope_parser.py new file mode 100644 index 0000000..d49acc2 --- /dev/null +++ b/cronitor/tests/envelope_parser.py @@ -0,0 +1,104 @@ +"""Test helpers: a small reference parser for envelope bytes and a fake send function. + +The parser is intentionally independent of cronitor.ingest so tests check the +bytes on the wire, not the code that produced them. +""" +import gzip +import json +import threading +import time + + +def parse_envelope(body, compressed=True): + """Parse envelope bytes into (header, [(item_header, payload), ...]). + + Layout: one JSON header line, then for each item a JSON item header line, + exactly `length` payload bytes, and a newline. + """ + raw = gzip.decompress(body) if compressed else body + header_line, sep, rest = raw.partition(b'\n') + if not sep: + raise AssertionError('envelope header is not newline terminated') + header = json.loads(header_line.decode('utf-8')) + items = [] + while rest: + item_header_line, sep, rest = rest.partition(b'\n') + if not sep: + raise AssertionError('item header is not newline terminated') + item_header = json.loads(item_header_line.decode('utf-8')) + if 'length' not in item_header: + raise AssertionError('item header has no length: %r' % item_header) + length = item_header['length'] + if len(rest) < length: + raise AssertionError('payload shorter than length %d' % length) + payload, rest = rest[:length], rest[length:] + if rest[:1] != b'\n': + raise AssertionError('payload is not followed by a newline') + rest = rest[1:] + items.append((item_header, json.loads(payload.decode('utf-8')))) + return header, items + + +class FakeResponse(object): + def __init__(self, status_code=200, headers=None): + self.status_code = status_code + self.headers = headers or {} + + +class SentRequest(object): + def __init__(self, url, data, headers, timeout): + self.url = url + self.data = data + self.headers = headers + self.timeout = timeout + + @property + def envelope(self): + return parse_envelope(self.data) + + +class RecordingSend(object): + """Injectable send(url, data, headers, timeout) that records every call.""" + + def __init__(self, responses=None, raises=None): + self.calls = [] + self.responses = list(responses or []) + self.raises = raises + self._lock = threading.Lock() + + def __call__(self, url, data, headers, timeout): + with self._lock: + self.calls.append(SentRequest(url, data, headers, timeout)) + if self.raises is not None: + raise self.raises + if self.responses: + return self.responses.pop(0) + return FakeResponse(200) + + def envelopes(self): + return [c.envelope for c in self.calls] + + def items(self, item_type=None): + out = [] + for _, items in self.envelopes(): + for item_header, payload in items: + if item_type is None or item_header['type'] == item_type: + out.append((item_header, payload)) + return out + + def events(self): + return [payload for _, payload in self.items('event')] + + def log_records(self): + records = [] + for _, payload in self.items('log'): + records.extend(payload['items']) + return records + + def wait_for(self, count, timeout=2.0): + deadline = time.time() + timeout + while time.time() < deadline: + if len(self.calls) >= count: + return True + time.sleep(0.01) + return len(self.calls) >= count diff --git a/cronitor/tests/test_ingest.py b/cronitor/tests/test_ingest.py new file mode 100644 index 0000000..8a67aae --- /dev/null +++ b/cronitor/tests/test_ingest.py @@ -0,0 +1,327 @@ +import gzip +import json +import os +import re +import subprocess +import sys +import threading +import unittest +from unittest.mock import patch + +import cronitor +from cronitor import ingest +from cronitor.tests.envelope_parser import FakeResponse, RecordingSend, parse_envelope + +FAKE_API_KEY = 'ingest-api-key' +REPO_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +RFC3339_UTC = re.compile(r'^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{6}Z$') + + +def _event(event_id='a' * 32, **fields): + event = {'event_id': event_id, 'level': 'error', 'platform': 'python'} + event.update(fields) + return event + + +def _record(body, level='info'): + return {'timestamp': 1761768000.5, 'level': level, 'body': body, 'attributes': {}} + + +class EnvelopeSerializationTests(unittest.TestCase): + + def test_serialize_envelope_layout(self): + raw = ingest.serialize_envelope({'event_id': 'b' * 32}, [({'type': 'event'}, b'{"x":1}')]) + self.assertEqual(raw, b'{"event_id":"' + b'b' * 32 + b'"}\n{"type":"event","length":7}\n{"x":1}\n') + + def test_length_counts_bytes_not_characters(self): + payload = json.dumps({'body': 'caf\u00e9 \u2603'}, ensure_ascii=False).encode('utf-8') + raw = ingest.serialize_envelope({}, [({'type': 'event'}, payload)]) + _, items = parse_envelope(raw, compressed=False) + self.assertEqual(items[0][0]['length'], len(payload)) + self.assertEqual(items[0][1]['body'], 'caf\u00e9 \u2603') + + def test_event_envelope(self): + payload = ingest.json_bytes(_event()) + header, items = parse_envelope(ingest.event_envelope(payload, 'a' * 32), compressed=False) + self.assertEqual(header['event_id'], 'a' * 32) + self.assertRegex(header['sent_at'], RFC3339_UTC) + self.assertEqual(header['sdk'], {'name': 'cronitor-python', 'version': ingest.SDK_VERSION}) + self.assertEqual(len(items), 1) + item_header, event = items[0] + self.assertEqual(item_header, {'type': 'event', 'content_type': 'application/json', 'length': len(payload)}) + self.assertEqual(event['event_id'], 'a' * 32) + + def test_log_envelope(self): + records = [_record('one'), _record('two', 'warn')] + header, items = parse_envelope(ingest.log_envelope(records), compressed=False) + self.assertNotIn('event_id', header) + self.assertRegex(header['sent_at'], RFC3339_UTC) + self.assertEqual(header['sdk']['name'], 'cronitor-python') + item_header, payload = items[0] + self.assertEqual(item_header['type'], 'log') + self.assertEqual(item_header['item_count'], 2) + self.assertEqual(item_header['content_type'], 'application/vnd.sentry.items.log+json') + self.assertIn('length', item_header) + self.assertEqual([r['body'] for r in payload['items']], ['one', 'two']) + + def test_format_timestamp(self): + from datetime import datetime, timezone + stamp = datetime(2026, 10, 29, 20, 0, 0, 123456, tzinfo=timezone.utc) + self.assertEqual(ingest.format_timestamp(stamp), '2026-10-29T20:00:00.123456Z') + + +class UrlTests(unittest.TestCase): + + def setUp(self): + self._saved = cronitor.ingest_url + + def tearDown(self): + cronitor.ingest_url = self._saved + + def test_default_urls_unchanged(self): + cronitor.ingest_url = ingest.DEFAULT_INGEST_URL + self.assertEqual(ingest.envelope_url(), 'https://cronitor.link/api/envelope') + monitor = cronitor.Monitor('my-job', api_key='abc') + self.assertEqual(monitor._ping_api_url(), 'https://cronitor.link/p/abc/my-job') + + def test_ingest_url_setting_moves_pings_and_envelopes(self): + cronitor.ingest_url = 'http://localhost:9100/' + self.assertEqual(ingest.envelope_url(), 'http://localhost:9100/api/envelope') + monitor = cronitor.Monitor('my-job', api_key='abc') + self.assertEqual(monitor._ping_api_url(), 'http://localhost:9100/p/abc/my-job') + + def test_unset_ingest_url_falls_back_to_default(self): + cronitor.ingest_url = None + self.assertEqual(ingest.envelope_url(), 'https://cronitor.link/api/envelope') + + def test_env_var_sets_ingest_url(self): + script = ( + 'import cronitor\n' + 'from cronitor import ingest\n' + 'print(cronitor.ingest_url)\n' + 'print(ingest.envelope_url())\n' + 'print(cronitor.Monitor("my-job", api_key="abc")._ping_api_url())\n' + ) + env = dict(os.environ, CRONITOR_INGEST_URL='http://localhost:9100') + env.pop('CRONITOR_CONFIG', None) + out = subprocess.run([sys.executable, '-c', script], cwd=REPO_ROOT, env=env, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=30) + self.assertEqual(out.returncode, 0, out.stderr) + self.assertEqual(out.stdout.decode().split(), [ + 'http://localhost:9100', + 'http://localhost:9100/api/envelope', + 'http://localhost:9100/p/abc/my-job', + ]) + + +class TransportTests(unittest.TestCase): + + def setUp(self): + self._saved_key = cronitor.api_key + self._saved_url = cronitor.ingest_url + cronitor.api_key = FAKE_API_KEY + cronitor.ingest_url = ingest.DEFAULT_INGEST_URL + self.sleeps = [] + self.send = RecordingSend() + self.transport = ingest.Transport(send=self.send, sleep=self.sleeps.append) + + def tearDown(self): + self.transport.flush(1.0) + cronitor.api_key = self._saved_key + cronitor.ingest_url = self._saved_url + + def test_event_is_sent_gzipped_with_headers(self): + self.assertTrue(self.transport.submit_event(_event())) + self.assertTrue(self.transport.flush(2.0)) + self.assertEqual(len(self.send.calls), 1) + call = self.send.calls[0] + self.assertEqual(call.url, 'https://cronitor.link/api/envelope') + self.assertEqual(call.timeout, 5) + self.assertEqual(call.headers, { + 'Content-Type': 'application/x-sentry-envelope', + 'Content-Encoding': 'gzip', + 'User-Agent': 'cronitor-python', + 'X-Sentry-Auth': 'Sentry sentry_key=%s, sentry_version=7, sentry_client=cronitor-python/%s' + % (FAKE_API_KEY, ingest.SDK_VERSION), + }) + self.assertEqual(call.data[:2], b'\x1f\x8b') + header, items = parse_envelope(call.data) + self.assertEqual(header['event_id'], 'a' * 32) + self.assertEqual(items[0][0]['type'], 'event') + + def test_one_envelope_per_event(self): + self.transport.submit_event(_event('1' * 32)) + self.transport.submit_event(_event('2' * 32)) + self.transport.flush(2.0) + self.assertEqual([h['event_id'] for h, _ in self.send.envelopes()], ['1' * 32, '2' * 32]) + for _, items in self.send.envelopes(): + self.assertEqual(len(items), 1) + + def test_api_key_and_url_are_taken_at_submit_time(self): + self.transport.submit_event(_event(), api_key='other-key') + cronitor.ingest_url = 'http://localhost:9100' + self.transport.submit_event(_event()) + self.transport.flush(2.0) + self.assertIn('sentry_key=other-key,', self.send.calls[0].headers['X-Sentry-Auth']) + self.assertEqual(self.send.calls[0].url, 'https://cronitor.link/api/envelope') + self.assertEqual(self.send.calls[1].url, 'http://localhost:9100/api/envelope') + + def test_no_api_key_sends_nothing(self): + cronitor.api_key = None + with self.assertLogs('cronitor.ingest', 'ERROR'): + self.assertFalse(self.transport.submit_event(_event())) + self.transport.flush(1.0) + self.assertEqual(self.send.calls, []) + + def test_logs_batch_until_flush(self): + for i in range(3): + self.transport.submit_log(_record('line %d' % i)) + self.assertTrue(self.transport.flush(2.0)) + self.assertEqual(len(self.send.calls), 1) + _, items = self.send.envelopes()[0] + self.assertEqual(items[0][0]['item_count'], 3) + self.assertEqual([r['body'] for r in items[0][1]['items']], ['line 0', 'line 1', 'line 2']) + + def test_logs_batch_by_count(self): + for i in range(250): + self.transport.submit_log(_record('line %d' % i)) + # two full batches go out without a flush + self.assertTrue(self.send.wait_for(2)) + self.transport.flush(2.0) + counts = [items[0][0]['item_count'] for _, items in self.send.envelopes()] + self.assertEqual(counts, [100, 100, 50]) + self.assertEqual(len(self.send.log_records()), 250) + + def test_logs_batch_by_time(self): + transport = ingest.Transport(send=self.send, batch_interval=0.1) + transport.submit_log(_record('late line')) + self.assertTrue(self.send.wait_for(1, timeout=2.0)) + self.assertEqual([r['body'] for r in self.send.log_records()], ['late line']) + + def test_events_do_not_wait_for_log_batch(self): + self.transport.submit_log(_record('buffered')) + self.transport.submit_event(_event()) + self.assertTrue(self.send.wait_for(1)) + self.assertEqual(self.send.items()[0][0]['type'], 'event') + self.transport.flush(2.0) + self.assertEqual([h['type'] for h, _ in self.send.items()], ['event', 'log']) + + def test_send_exception_is_swallowed_and_logged(self): + self.send.raises = ConnectionError('network down') + with self.assertLogs('cronitor.ingest', 'WARNING') as logs: + self.assertTrue(self.transport.submit_event(_event())) + self.assertTrue(self.transport.flush(2.0)) + self.assertIn('network down', '\n'.join(logs.output)) + # the worker survives and keeps sending + self.send.raises = None + self.transport.submit_event(_event('c' * 32)) + self.transport.flush(2.0) + self.assertEqual(len(self.send.calls), 2) + + def test_error_status_is_logged(self): + self.send.responses = [FakeResponse(403)] + with self.assertLogs('cronitor.ingest', 'WARNING') as logs: + self.transport.submit_event(_event()) + self.transport.flush(2.0) + self.assertIn('403', '\n'.join(logs.output)) + + def test_429_sleeps_retry_after_before_next_send(self): + self.send.responses = [FakeResponse(429, {'Retry-After': '7'})] + with self.assertLogs('cronitor.ingest', 'WARNING'): + self.transport.submit_event(_event('1' * 32)) + self.transport.flush(2.0) + self.assertEqual(self.sleeps, []) + self.transport.submit_event(_event('2' * 32)) + self.transport.flush(2.0) + self.assertEqual(len(self.sleeps), 1) + self.assertAlmostEqual(self.sleeps[0], 7, delta=1) + self.assertEqual(len(self.send.calls), 2) + + def test_429_retry_after_is_capped_at_60_seconds(self): + self.send.responses = [FakeResponse(429, {'Retry-After': '3600'})] + with self.assertLogs('cronitor.ingest', 'WARNING'): + self.transport.submit_event(_event('1' * 32)) + self.transport.flush(2.0) + self.transport.submit_log(_record('after the limit')) + self.transport.flush(2.0) + self.assertEqual(len(self.sleeps), 1) + self.assertLessEqual(self.sleeps[0], 60) + self.assertGreater(self.sleeps[0], 58) + + def test_429_without_retry_after_waits_60_seconds(self): + self.send.responses = [FakeResponse(429)] + with self.assertLogs('cronitor.ingest', 'WARNING'): + self.transport.submit_event(_event('1' * 32)) + self.transport.flush(2.0) + self.transport.submit_event(_event('2' * 32)) + self.transport.flush(2.0) + self.assertGreater(self.sleeps[0], 58) + + def test_full_queue_drops_and_counts(self): + release = threading.Event() + started = threading.Event() + + def blocking_send(url, data, headers, timeout): + started.set() + release.wait(5) + return FakeResponse(200) + + transport = ingest.Transport(send=blocking_send, maxsize=2) + transport.submit_event(_event('0' * 32)) + self.assertTrue(started.wait(2)) + results = [transport.submit_event(_event(str(i) * 32)) for i in range(1, 6)] + self.assertEqual(results, [True, True, False, False, False]) + self.assertEqual(transport.dropped, 3) + release.set() + self.assertTrue(transport.flush(2.0)) + + def test_flush_without_activity_returns_immediately(self): + transport = ingest.Transport(send=self.send) + self.assertTrue(transport.flush(0.1)) + self.assertEqual(self.send.calls, []) + + def test_new_worker_after_fork(self): + self.transport.submit_event(_event('1' * 32)) + self.transport.flush(2.0) + first_thread = self.transport._thread + # simulate running in a forked child: the parent's thread does not exist there + with patch('os.getpid', return_value=os.getpid() + 100000): + self.transport.submit_event(_event('2' * 32)) + self.assertTrue(self.transport.flush(2.0)) + self.assertIsNot(self.transport._thread, first_thread) + self.assertEqual(len(self.send.calls), 2) + + +class ModuleTransportTests(unittest.TestCase): + + def test_set_transport_returns_previous(self): + replacement = ingest.Transport(send=RecordingSend()) + previous = ingest.set_transport(replacement) + try: + self.assertIs(ingest.get_transport(), replacement) + finally: + ingest.set_transport(previous) + self.assertIs(ingest.get_transport(), previous) + + def test_flush_at_exit(self): + script = ( + 'import sys, gzip\n' + 'import cronitor\n' + 'from cronitor import ingest\n' + 'class R(object):\n' + ' status_code = 200\n' + ' headers = {}\n' + 'def send(url, data, headers, timeout):\n' + ' sys.stdout.write("SENT %d\\n" % gzip.decompress(data).count(b"\\n"))\n' + ' sys.stdout.flush()\n' + ' return R()\n' + 'ingest.set_transport(ingest.Transport(send=send))\n' + 'cronitor.api_key = "k"\n' + 'ingest.submit_log({"timestamp": 1.0, "level": "info", "body": "bye", "attributes": {}})\n' + ) + env = dict(os.environ) + env.pop('CRONITOR_CONFIG', None) + out = subprocess.run([sys.executable, '-c', script], cwd=REPO_ROOT, env=env, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=30) + self.assertEqual(out.returncode, 0, out.stderr) + self.assertEqual(out.stdout.decode().strip(), 'SENT 3') From 281aa05e0ab0360bfc350eeb4a4d2703ad202ad0 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 29 Oct 2026 21:00:03 +0000 Subject: [PATCH 02/18] Add capture_exception, capture_message and cronitor.logger cronitor/capture.py builds exception and message events and structured log records. Exceptions follow __cause__ then __context__, oldest first, with frames oldest first, five lines of source context from linecache, and in_app false for site-packages, dist-packages and the stdlib. Local variables are never sent. Values, messages and log bodies are truncated to 4000/4000/8000 characters and tags and attributes to 50 entries. cronitor.logger mirrors sentry_sdk.logger: the body is formatted with str.format when attributes and braces are present, and the template and parameters are recorded as sentry.message.* attributes. It replaces the stdlib logger that was exported under that name; its configuration methods still delegate to logging.getLogger('cronitor'). Monitor.capture_exception and Monitor.capture_message bind the monitor key, environment and API key. New settings: cronitor.release (env CRONITOR_RELEASE) and cronitor.capture_exceptions. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01B4Z4DjN96ccpNoVRZuoCxo --- cronitor/__init__.py | 14 +- cronitor/capture.py | 445 +++++++++++++++++++++++++++++++++ cronitor/monitor.py | 12 + cronitor/tests/test_capture.py | 405 ++++++++++++++++++++++++++++++ 4 files changed, 872 insertions(+), 4 deletions(-) create mode 100644 cronitor/capture.py create mode 100644 cronitor/tests/test_capture.py diff --git a/cronitor/__init__.py b/cronitor/__init__.py index d701c42..9ab4540 100644 --- a/cronitor/__init__.py +++ b/cronitor/__init__.py @@ -12,9 +12,11 @@ from .monitor import Monitor, YAML from . import ingest from .ingest import flush +from .capture import capture_exception, capture_message, logger -logger = logging.getLogger(__name__) -logger.setLevel(logging.INFO) +# the package's own diagnostics; `cronitor.logger` ships structured logs to Cronitor +_logger = logging.getLogger(__name__) +_logger.setLevel(logging.INFO) # configuration variables api_key = os.getenv('CRONITOR_API_KEY', None) @@ -27,6 +29,10 @@ # base URL for telemetry pings and exception/log envelopes, e.g. http://localhost:9100 in development ingest_url = os.getenv('CRONITOR_INGEST_URL') or ingest.DEFAULT_INGEST_URL +# attached to exception events and logs +release = os.getenv('CRONITOR_RELEASE', None) +# send an exception event when a function decorated with @cronitor.job raises +capture_exceptions = True celerybeat_only = False @@ -108,10 +114,10 @@ def apply_config(rollback=False): check_count = len(monitors.get('checks', [])) heartbeat_count = len(monitors.get('heartbeats', [])) total_count = sum([job_count, check_count, heartbeat_count]) - logger.info('{} monitor{} {}'.format(total_count, 's' if total_count != 1 else '', 'validated.' if rollback else 'synced.',)) + _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: - logger.error(e) + _logger.error(e) return False def read_config(path=None, output=False): diff --git a/cronitor/capture.py b/cronitor/capture.py new file mode 100644 index 0000000..e722c6f --- /dev/null +++ b/cronitor/capture.py @@ -0,0 +1,445 @@ +"""Exception, message and log capture. + +Events and log records are bound to a monitor and a run with the reserved +names ``cronitor.monitor`` and ``cronitor.series`` (tags on events, attributes +on logs). Inside ``@cronitor.job`` both are filled in automatically. +""" +import contextvars +import linecache +import logging +import os +import socket +import sys +import sysconfig +import time +import traceback +import uuid +from collections import namedtuple + +import cronitor +from . import ingest + +_log = logging.getLogger(__name__) + +MONITOR_TAG = 'cronitor.monitor' +SERIES_TAG = 'cronitor.series' + +MAX_VALUE_LENGTH = 4000 +MAX_MESSAGE_LENGTH = 4000 +MAX_LOG_BODY_LENGTH = 8000 +MAX_TAGS = 50 +MAX_TAG_KEY_LENGTH = 64 +MAX_TAG_VALUE_LENGTH = 400 +MAX_ATTRIBUTES = 50 +MAX_ATTRIBUTE_VALUE_LENGTH = 8000 +MAX_CHAINED_EXCEPTIONS = 10 +MAX_FRAMES = 100 +MAX_LINE_LENGTH = 1000 +CONTEXT_LINES = 5 + +EVENT_LEVELS = { + 'fatal': 'fatal', 'critical': 'fatal', 'error': 'error', 'warning': 'warning', + 'warn': 'warning', 'info': 'info', 'debug': 'debug', +} +LOG_SEVERITY = {'trace': 1, 'debug': 5, 'info': 9, 'warn': 13, 'error': 17, 'fatal': 21} + +JobContext = namedtuple('JobContext', ['monitor', 'series', 'env']) +_current_job = contextvars.ContextVar('cronitor_job', default=None) + + +def current_job(): + """The (monitor, series, env) of the enclosing ``@cronitor.job``, or None.""" + return _current_job.get() + + +def bind_job(monitor, series, env): + """Bind captures in this context to a run. Returns a token for ``unbind_job``.""" + return _current_job.set(JobContext(monitor, series, env)) + + +def unbind_job(token): + _current_job.reset(token) + + +# public API + +def capture_exception(exc=None, *, monitor=None, series=None, level='error', tags=None, extra=None): + """Send an exception event. ``exc`` defaults to the exception being handled. + + Returns the event id, or None when nothing was sent. + """ + return _capture_exception(exc, monitor=monitor, series=series, level=level, tags=tags, extra=extra) + + +def capture_message(message, level='info', *, monitor=None, series=None, tags=None, extra=None): + """Send a message event. Returns the event id, or None when nothing was sent.""" + return _capture_message(message, level=level, monitor=monitor, series=series, tags=tags, extra=extra) + + +class Logger(object): + """Structured logs shipped to Cronitor, mirroring ``sentry_sdk.logger``. + + ``cronitor.logger.info('processed {count} rows', count=5)`` formats the body + with ``str.format`` and records the template and parameters as attributes. + """ + + def trace(self, body, **attributes): + _capture_log('trace', body, attributes) + + def debug(self, body, **attributes): + _capture_log('debug', body, attributes) + + def info(self, body, **attributes): + _capture_log('info', body, attributes) + + def warning(self, body, **attributes): + _capture_log('warn', body, attributes) + + def error(self, body, **attributes): + _capture_log('error', body, attributes) + + def fatal(self, body, **attributes): + _capture_log('fatal', body, attributes) + + # Before 5.0 `cronitor.logger` was logging.getLogger('cronitor'). Keep its + # configuration methods working so existing setup code does not break. + _STDLIB_CONFIG = frozenset(['setLevel', 'getEffectiveLevel', 'isEnabledFor', 'addHandler', + 'removeHandler', 'hasHandlers', 'addFilter', 'removeFilter', + 'handlers', 'filters', 'level', 'name', 'propagate', 'disabled']) + + def __getattr__(self, name): + if name in Logger._STDLIB_CONFIG: + return getattr(logging.getLogger('cronitor'), name) + raise AttributeError(name) + + +logger = Logger() + + +# events + +def _capture_exception(exc, monitor=None, series=None, level='error', tags=None, extra=None, + env=None, api_key=None, mechanism='generic', handled=True): + try: + exc_info = _exc_info(exc) + if exc_info is None: + return None + event = _base_event(level, monitor, series, tags, extra, env) + event['exception'] = {'values': _exception_values(exc_info, mechanism, handled)} + return _submit_event(event, api_key) + except Exception as e: + _log.warning('Cronitor could not capture an exception: %s', e) + return None + + +def _capture_message(message, level='info', monitor=None, series=None, tags=None, extra=None, + env=None, api_key=None): + try: + event = _base_event(level, monitor, series, tags, extra, env) + event['message'] = {'formatted': _truncate(_safe_str(message), MAX_MESSAGE_LENGTH)} + return _submit_event(event, api_key) + except Exception as e: + _log.warning('Cronitor could not capture a message: %s', e) + return None + + +def _submit_event(event, api_key): + if ingest.submit_event(event, api_key=api_key): + return event['event_id'] + return None + + +def _exc_info(exc): + if exc is None: + exc_info = sys.exc_info() + elif isinstance(exc, BaseException): + exc_info = (type(exc), exc, exc.__traceback__) + elif isinstance(exc, tuple) and len(exc) == 3: + exc_info = exc + else: + _log.warning('Cronitor capture_exception() expects an exception, got %s', type(exc).__name__) + return None + if exc_info[0] is None or exc_info[1] is None: + return None + return exc_info + + +def _binding(monitor, series, env): + """Resolve monitor, series and env: explicit values first, then the enclosing job.""" + job = _current_job.get() + if job is not None and (monitor is None or monitor == job.monitor): + monitor = job.monitor + if series is None: + series = job.series + if env is None: + env = job.env + return monitor, series, env or cronitor.environment + + +def _base_event(level, monitor, series, tags, extra, env): + user_tags = dict(tags or {}) + if monitor is None: + monitor = user_tags.get(MONITOR_TAG) + if series is None: + series = user_tags.get(SERIES_TAG) + monitor, series, env = _binding(monitor, series, env) + + bound = {} + if monitor is not None: + bound[MONITOR_TAG] = monitor + if series is not None: + bound[SERIES_TAG] = series + event_tags = {} + for key, value in list(bound.items()) + list(user_tags.items()): + key = _truncate(_safe_str(key), MAX_TAG_KEY_LENGTH) + if key in event_tags or len(event_tags) >= MAX_TAGS: + continue + event_tags[key] = _truncate(_safe_str(value), MAX_TAG_VALUE_LENGTH) + + event = { + 'event_id': uuid.uuid4().hex, + 'timestamp': ingest.format_timestamp(), + 'platform': 'python', + 'level': EVENT_LEVELS.get(_safe_str(level).lower(), 'error'), + 'server_name': _hostname(), + 'tags': event_tags, + 'extra': dict(extra or {}), + 'sdk': ingest.sdk_info(), + } + if cronitor.release: + event['release'] = _safe_str(cronitor.release) + if env: + event['environment'] = _safe_str(env) + return event + + +def _walk_chain(exc_info): + """Yield (type, value, tb) newest first, following __cause__, then __context__.""" + exc_type, exc_value, tb = exc_info + seen = set() + while exc_type is not None and exc_value is not None and id(exc_value) not in seen: + yield exc_type, exc_value, tb + seen.add(id(exc_value)) + if exc_value.__cause__ is not None: + cause = exc_value.__cause__ + elif not exc_value.__suppress_context__: + cause = exc_value.__context__ + else: + cause = None + if cause is None: + break + exc_type, exc_value, tb = type(cause), cause, cause.__traceback__ + + +def _exception_values(exc_info, mechanism, handled): + chain = [] + for link in _walk_chain(exc_info): + chain.append(link) + if len(chain) >= MAX_CHAINED_EXCEPTIONS: + break + values = [] + for exc_type, exc_value, tb in reversed(chain): + values.append({ + 'type': getattr(exc_type, '__name__', _safe_str(exc_type)), + 'value': _truncate(_safe_str(exc_value), MAX_VALUE_LENGTH), + 'module': _type_module(exc_type), + 'mechanism': {'type': mechanism, 'handled': handled}, + 'stacktrace': {'frames': _frames(tb)}, + }) + return values + + +def _type_module(exc_type): + module = getattr(exc_type, '__module__', None) + if module in ('builtins', '__builtin__', 'exceptions'): + return None + return module + + +def _frames(tb): + """Frames oldest first, the crash site last. Very deep stacks keep both ends.""" + entries = list(traceback.walk_tb(tb)) + if len(entries) > MAX_FRAMES: + half = MAX_FRAMES // 2 + entries = entries[:half] + entries[-half:] + return [_frame(frame, lineno) for frame, lineno in entries] + + +def _frame(frame, lineno): + code = frame.f_code + path = code.co_filename or '' + module = frame.f_globals.get('__name__') + abs_path = path if path.startswith('<') else os.path.abspath(path) + pre_context, context_line, post_context = _source_context(path, lineno, frame.f_globals) + return { + 'filename': _filename_for_module(module, abs_path), + 'abs_path': abs_path, + 'function': code.co_name, + 'module': module, + 'lineno': lineno, + 'context_line': context_line, + 'pre_context': pre_context, + 'post_context': post_context, + 'in_app': _in_app(abs_path), + } + + +def _source_context(path, lineno, module_globals): + try: + lines = linecache.getlines(path, module_globals) + except Exception: + lines = [] + if not lines or not lineno or lineno > len(lines): + return [], None, [] + index = lineno - 1 + clean = [_truncate(line.rstrip('\r\n'), MAX_LINE_LENGTH) for line in + lines[max(0, index - CONTEXT_LINES):index + CONTEXT_LINES + 1]] + offset = index - max(0, index - CONTEXT_LINES) + return clean[:offset], clean[offset], clean[offset + 1:] + + +def _filename_for_module(module, abs_path): + """A path relative to the top-level package, like Sentry, e.g. myapp/jobs/nightly.py.""" + if not module or abs_path.startswith('<'): + return abs_path + try: + if abs_path.endswith('.pyc'): + abs_path = abs_path[:-1] + base_module = module.split('.', 1)[0] + if base_module == module: + return os.path.basename(abs_path) + base_path = getattr(sys.modules.get(base_module), '__file__', None) + if not base_path: + return abs_path + return abs_path.split(base_path.rsplit(os.sep, 2)[0], 1)[-1].lstrip(os.sep) + except Exception: + return abs_path + + +_stdlib_prefixes = None + + +def _library_prefixes(): + global _stdlib_prefixes + if _stdlib_prefixes is None: + prefixes = set() + paths = sysconfig.get_paths() + for name in ('stdlib', 'platstdlib'): + path = paths.get(name) + if path: + for candidate in (path, os.path.realpath(path)): + prefixes.add(candidate.rstrip(os.sep) + os.sep) + _stdlib_prefixes = tuple(prefixes) + return _stdlib_prefixes + + +def _in_app(abs_path): + if abs_path.startswith('<'): + return not abs_path.startswith('= MAX_ATTRIBUTES: + continue + attrs[key] = value + + return { + 'timestamp': time.time() if timestamp is None else float(timestamp), + 'level': level, + 'body': _truncate(body, MAX_LOG_BODY_LENGTH), + 'attributes': {key: _typed(value) for key, value in attrs.items()}, + } + + +def _typed(value): + if isinstance(value, bool): + return {'value': value, 'type': 'boolean'} + if isinstance(value, int): + return {'value': value, 'type': 'integer'} + if isinstance(value, float): + return {'value': value, 'type': 'double'} + if not isinstance(value, str): + value = _safe_repr(value) + return {'value': _truncate(value, MAX_ATTRIBUTE_VALUE_LENGTH), 'type': 'string'} + + +# helpers + +def _hostname(): + try: + return socket.gethostname() + except Exception: + return '' + + +def _truncate(value, length): + return value if len(value) <= length else value[:length] + + +def _safe_str(value): + if isinstance(value, str): + return value + try: + return str(value) + except Exception: + return _safe_repr(value) + + +def _safe_repr(value): + try: + return repr(value) + except Exception: + return '' % type(value).__name__ diff --git a/cronitor/monitor.py b/cronitor/monitor.py index b3902ef..6813176 100644 --- a/cronitor/monitor.py +++ b/cronitor/monitor.py @@ -169,6 +169,18 @@ def ping(self, **params): def ok(self): self.ping(state=cronitor.State.OK) + def capture_exception(self, exc=None, *, series=None, level='error', tags=None, extra=None): + """Send an exception event bound to this monitor and its environment.""" + from .capture import _capture_exception + return _capture_exception(exc, monitor=self.key, series=series, level=level, tags=tags, + extra=extra, env=self.env, api_key=self.api_key) + + def capture_message(self, message, level='info', *, series=None, tags=None, extra=None): + """Send a message event bound to this monitor and its environment.""" + from .capture import _capture_message + return _capture_message(message, level=level, monitor=self.key, series=series, tags=tags, + extra=extra, env=self.env, api_key=self.api_key) + def pause(self, hours): if not self.api_key: logger.error('No API key detected. Set cronitor.api_key or initialize Monitor with kwarg api_key.') diff --git a/cronitor/tests/test_capture.py b/cronitor/tests/test_capture.py new file mode 100644 index 0000000..50abc12 --- /dev/null +++ b/cronitor/tests/test_capture.py @@ -0,0 +1,405 @@ +import json +import os +import re +import socket +import time +import unittest + +import cronitor +from cronitor import ingest +from cronitor.tests.envelope_parser import RecordingSend + +FAKE_API_KEY = 'capture-api-key' +HEX32 = re.compile(r'^[0-9a-f]{32}$') +RFC3339_UTC = re.compile(r'^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{6}Z$') +FRAME_KEYS = {'filename', 'abs_path', 'function', 'module', 'lineno', + 'context_line', 'pre_context', 'post_context', 'in_app'} + + +def _inner(): + raise ValueError('inner boom') + + +def _outer(): + try: + _inner() + except ValueError as e: + raise RuntimeError('outer boom') from e + + +def _attr(record, name): + return record['attributes'][name] + + +class CaptureTestCase(unittest.TestCase): + """Installs a recording transport and known settings for each test.""" + + def setUp(self): + self._saved = {name: getattr(cronitor, name) for name in + ('api_key', 'ingest_url', 'environment', 'release', 'capture_exceptions')} + cronitor.api_key = FAKE_API_KEY + cronitor.ingest_url = ingest.DEFAULT_INGEST_URL + cronitor.environment = None + cronitor.release = None + cronitor.capture_exceptions = True + self.send = RecordingSend() + self._previous_transport = ingest.set_transport(ingest.Transport(send=self.send)) + + def tearDown(self): + ingest.set_transport(self._previous_transport) + for name, value in self._saved.items(): + setattr(cronitor, name, value) + + def flushed_events(self): + self.assertTrue(cronitor.flush(2.0)) + return self.send.events() + + def flushed_logs(self): + self.assertTrue(cronitor.flush(2.0)) + return self.send.log_records() + + def only_event(self): + events = self.flushed_events() + self.assertEqual(len(events), 1, events) + return events[0] + + +class CaptureExceptionTests(CaptureTestCase): + + def test_chained_cause_is_two_values_oldest_first(self): + try: + _outer() + except RuntimeError as e: + event_id = cronitor.capture_exception(e) + + self.assertRegex(event_id, HEX32) + self.assertTrue(cronitor.flush(2.0)) + header, items = self.send.envelopes()[0] + self.assertEqual(header['event_id'], event_id) + self.assertEqual([h['type'] for h, _ in items], ['event']) + event = items[0][1] + self.assertEqual(event['event_id'], event_id) + + values = event['exception']['values'] + self.assertEqual([v['type'] for v in values], ['ValueError', 'RuntimeError']) + self.assertEqual([v['value'] for v in values], ['inner boom', 'outer boom']) + self.assertEqual([v['module'] for v in values], [None, None]) + for value in values: + self.assertEqual(value['mechanism'], {'type': 'generic', 'handled': True}) + + cause_frames = values[0]['stacktrace']['frames'] + self.assertEqual([f['function'] for f in cause_frames], ['_outer', '_inner']) + self.assertEqual(cause_frames[-1]['context_line'].strip(), "raise ValueError('inner boom')") + self.assertEqual(cause_frames[-1]['pre_context'][-1].strip(), 'def _inner():') + + frames = values[1]['stacktrace']['frames'] + self.assertEqual([f['function'] for f in frames], + ['test_chained_cause_is_two_values_oldest_first', '_outer']) + self.assertEqual(frames[-1]['context_line'].strip(), "raise RuntimeError('outer boom') from e") + + here = os.path.abspath(__file__) + for frame in cause_frames + frames: + self.assertEqual(set(frame), FRAME_KEYS) + self.assertEqual(frame['abs_path'], here) + self.assertEqual(frame['filename'], os.path.join('cronitor', 'tests', 'test_capture.py')) + self.assertEqual(frame['module'], __name__) + self.assertIsInstance(frame['lineno'], int) + self.assertTrue(frame['in_app']) + self.assertEqual(len(frame['pre_context']), 5) + self.assertLessEqual(len(frame['post_context']), 5) + self.assertNotIn('vars', frame) + + def test_implicit_context_is_chained(self): + try: + try: + raise KeyError('first') + except KeyError: + raise TypeError('second') + except TypeError as e: + cronitor.capture_exception(e) + values = self.only_event()['exception']['values'] + self.assertEqual([v['type'] for v in values], ['KeyError', 'TypeError']) + + def test_raise_from_none_suppresses_context(self): + try: + try: + raise KeyError('first') + except KeyError: + raise TypeError('second') from None + except TypeError as e: + cronitor.capture_exception(e) + values = self.only_event()['exception']['values'] + self.assertEqual([v['type'] for v in values], ['TypeError']) + + def test_custom_exception_module(self): + try: + raise cronitor.APIError('nope') + except cronitor.APIError as e: + cronitor.capture_exception(e) + value = self.only_event()['exception']['values'][0] + self.assertEqual(value['type'], 'APIError') + self.assertEqual(value['module'], 'cronitor') + + def test_library_frames_are_not_in_app(self): + try: + json.loads('{not json') + except ValueError as e: + cronitor.capture_exception(e) + frames = self.only_event()['exception']['values'][-1]['stacktrace']['frames'] + self.assertTrue(frames[0]['in_app']) + self.assertTrue(frames[-1]['abs_path'].endswith(os.path.join('json', 'decoder.py'))) + self.assertFalse(frames[-1]['in_app']) + self.assertEqual(frames[-1]['module'], 'json.decoder') + + def test_in_app_rules(self): + from cronitor.capture import _in_app + self.assertFalse(_in_app('/venv/lib/python3.8/site-packages/requests/api.py')) + self.assertFalse(_in_app('/usr/lib/python3/dist-packages/yaml/__init__.py')) + self.assertFalse(_in_app(json.__file__)) + self.assertFalse(_in_app('')) + self.assertTrue(_in_app('/srv/app/jobs/nightly.py')) + + def test_defaults_to_current_exception(self): + try: + raise LookupError('current') + except LookupError: + event_id = cronitor.capture_exception() + event = self.only_event() + self.assertEqual(event['event_id'], event_id) + self.assertEqual(event['exception']['values'][0]['type'], 'LookupError') + + def test_no_current_exception_sends_nothing(self): + self.assertIsNone(cronitor.capture_exception()) + self.assertEqual(self.flushed_events(), []) + + def test_event_fields(self): + cronitor.environment = 'production' + cronitor.release = '1.2.3' + try: + raise ValueError('x') + except ValueError as e: + cronitor.capture_exception(e, level='fatal') + event = self.only_event() + self.assertRegex(event['timestamp'], RFC3339_UTC) + self.assertEqual(event['platform'], 'python') + self.assertEqual(event['level'], 'fatal') + self.assertEqual(event['server_name'], socket.gethostname()) + self.assertEqual(event['environment'], 'production') + self.assertEqual(event['release'], '1.2.3') + self.assertEqual(event['sdk'], {'name': 'cronitor-python', 'version': ingest.SDK_VERSION}) + self.assertEqual(event['tags'], {}) + self.assertEqual(event['extra'], {}) + + def test_optional_fields_omitted_when_unset(self): + cronitor.capture_message('hello') + event = self.only_event() + self.assertNotIn('environment', event) + self.assertNotIn('release', event) + + def test_value_is_truncated(self): + try: + raise ValueError('v' * 5000) + except ValueError as e: + cronitor.capture_exception(e) + self.assertEqual(len(self.only_event()['exception']['values'][0]['value']), 4000) + + def test_deep_recursion_keeps_both_ends(self): + def recurse(n): + if n == 0: + raise ValueError('bottom') + return recurse(n - 1) + try: + recurse(300) + except ValueError as e: + cronitor.capture_exception(e) + frames = self.only_event()['exception']['values'][0]['stacktrace']['frames'] + self.assertLessEqual(len(frames), 100) + self.assertEqual(frames[0]['function'], 'test_deep_recursion_keeps_both_ends') + self.assertEqual(frames[-1]['context_line'].strip(), "raise ValueError('bottom')") + + def test_not_an_exception_sends_nothing(self): + with self.assertLogs('cronitor.capture', 'WARNING'): + self.assertIsNone(cronitor.capture_exception('not an exception')) + self.assertEqual(self.flushed_events(), []) + + def test_no_api_key_sends_nothing(self): + cronitor.api_key = None + try: + raise ValueError('x') + except ValueError as e: + with self.assertLogs('cronitor.ingest', 'ERROR'): + self.assertIsNone(cronitor.capture_exception(e)) + self.assertEqual(self.flushed_events(), []) + + +class CaptureMessageTests(CaptureTestCase): + + def test_message_event(self): + event_id = cronitor.capture_message('disk almost full') + self.assertTrue(cronitor.flush(2.0)) + header, items = self.send.envelopes()[0] + self.assertEqual(header['event_id'], event_id) + event = items[0][1] + self.assertEqual(event['message'], {'formatted': 'disk almost full'}) + self.assertEqual(event['level'], 'info') + self.assertNotIn('exception', event) + + def test_level_and_truncation(self): + cronitor.capture_message('m' * 5000, level='warning') + event = self.only_event() + self.assertEqual(event['level'], 'warning') + self.assertEqual(len(event['message']['formatted']), 4000) + + def test_tags_extra_and_bindings(self): + cronitor.capture_message('hi', monitor='nightly-backup', series='run-1', + tags={'region': 'us-east-1', 'attempt': 2}, extra={'rows': [1, 2], 'obj': object()}) + event = self.only_event() + self.assertEqual(event['tags'], { + 'cronitor.monitor': 'nightly-backup', + 'cronitor.series': 'run-1', + 'region': 'us-east-1', + 'attempt': '2', + }) + self.assertEqual(event['extra']['rows'], [1, 2]) + self.assertTrue(event['extra']['obj'].startswith(' Date: Thu, 29 Oct 2026 21:01:01 +0000 Subject: [PATCH 03/18] Capture exceptions raised inside @cronitor.job The decorator binds the monitor key, series and environment in a context variable while the function runs, so capture_exception, capture_message and cronitor.logger calls inside it are tagged with cronitor.monitor and cronitor.series. When the function raises, the decorator sends the fail ping as before and then an exception event bound to the same series, with mechanism cronitor.job and handled false. Set cronitor.capture_exceptions = False to send only the ping. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01B4Z4DjN96ccpNoVRZuoCxo --- cronitor/__init__.py | 10 +++- cronitor/tests/test_capture.py | 105 +++++++++++++++++++++++++++++++++ cronitor/tests/test_pings.py | 5 ++ 3 files changed, 119 insertions(+), 1 deletion(-) diff --git a/cronitor/__init__.py b/cronitor/__init__.py index 9ab4540..9a3c3db 100644 --- a/cronitor/__init__.py +++ b/cronitor/__init__.py @@ -10,7 +10,7 @@ import threading from .monitor import Monitor, YAML -from . import ingest +from . import capture, ingest from .ingest import flush from .capture import capture_exception, capture_message, logger @@ -80,12 +80,20 @@ 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) + # exceptions and logs captured while the function runs are bound to this run + 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) + if this.capture_exceptions: + 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 diff --git a/cronitor/tests/test_capture.py b/cronitor/tests/test_capture.py index 50abc12..da17179 100644 --- a/cronitor/tests/test_capture.py +++ b/cronitor/tests/test_capture.py @@ -4,6 +4,7 @@ import socket import time import unittest +from unittest.mock import patch import cronitor from cronitor import ingest @@ -403,3 +404,107 @@ def test_logs_are_batched_into_one_envelope(self): self.flushed_logs() self.assertEqual(len(self.send.calls), 1) self.assertEqual(self.send.items('log')[0][0]['item_count'], 3) + + +@cronitor.job('capture-job-test') +def _successful_job(): + return 'done' + + +@cronitor.job('capture-job-test') +def _failing_job(): + raise ValueError('job exploded') + + +@cronitor.job('capture-job-test', env='staging') +def _job_that_reports(): + cronitor.capture_message('inside the job') + cronitor.logger.info('log inside the job') + try: + raise KeyError('handled inside') + except KeyError as e: + cronitor.capture_exception(e) + cronitor.capture_message('other monitor', monitor='someone-else') + return 'ok' + + +class JobTests(CaptureTestCase): + + def setUp(self): + super().setUp() + patcher = patch('cronitor.Monitor.ping') + self.ping = patcher.start() + self.addCleanup(patcher.stop) + + def _ping_calls(self, state): + return [c for c in self.ping.call_args_list if c.kwargs.get('state') == state] + + def test_success_sends_no_event(self): + self.assertEqual(_successful_job(), 'done') + self.assertEqual(len(self._ping_calls('complete')), 1) + self.assertEqual(self.flushed_events(), []) + + def test_failure_sends_fail_ping_then_unhandled_event_with_same_series(self): + order = [] + self.ping.side_effect = lambda **params: order.append('ping:' + params['state']) + real_submit = ingest.submit_event + + def submit(event, api_key=None): + order.append('event') + return real_submit(event, api_key=api_key) + + with patch('cronitor.ingest.submit_event', side_effect=submit): + with self.assertRaises(ValueError): + _failing_job() + + self.assertEqual(order, ['ping:run', 'ping:fail', 'event']) + fail = self._ping_calls('fail')[0] + series = fail.kwargs['series'] + self.assertEqual(self._ping_calls('run')[0].kwargs['series'], series) + + event = self.only_event() + self.assertEqual(event['level'], 'error') + self.assertEqual(event['tags'], {'cronitor.monitor': 'capture-job-test', 'cronitor.series': str(series)}) + values = event['exception']['values'] + self.assertEqual(len(values), 1) + self.assertEqual(values[0]['type'], 'ValueError') + self.assertEqual(values[0]['value'], 'job exploded') + self.assertEqual(values[0]['mechanism'], {'type': 'cronitor.job', 'handled': False}) + self.assertEqual(values[0]['stacktrace']['frames'][-1]['function'], '_failing_job') + + def test_capture_exceptions_false_sends_no_event(self): + cronitor.capture_exceptions = False + with self.assertRaises(ValueError): + _failing_job() + self.assertEqual(len(self._ping_calls('fail')), 1) + self.assertEqual(self.flushed_events(), []) + + def test_captures_inside_a_job_bind_to_the_run(self): + cronitor.environment = 'production' + self.assertEqual(_job_that_reports(), 'ok') + series = str(self._ping_calls('run')[0].kwargs['series']) + bound = {'cronitor.monitor': 'capture-job-test', 'cronitor.series': series} + + events = self.flushed_events() + self.assertEqual(len(events), 3) + message, handled, other = events + self.assertEqual(message['tags'], bound) + self.assertEqual(message['environment'], 'staging') + self.assertEqual(handled['tags'], bound) + self.assertEqual(handled['exception']['values'][0]['mechanism'], {'type': 'generic', 'handled': True}) + # an explicit other monitor is not bound to this run or its environment + self.assertEqual(other['tags'], {'cronitor.monitor': 'someone-else'}) + self.assertEqual(other['environment'], 'production') + + record = self.send.log_records()[0] + self.assertEqual(_attr(record, 'cronitor.monitor')['value'], 'capture-job-test') + self.assertEqual(_attr(record, 'cronitor.series')['value'], series) + self.assertEqual(_attr(record, 'sentry.environment')['value'], 'staging') + + def test_binding_ends_with_the_job(self): + _successful_job() + with self.assertRaises(ValueError): + _failing_job() + self.assertIsNone(cronitor.capture.current_job()) + cronitor.capture_message('after the job') + self.assertEqual(self.flushed_events()[-1]['tags'], {}) diff --git a/cronitor/tests/test_pings.py b/cronitor/tests/test_pings.py index f53e996..a320623 100644 --- a/cronitor/tests/test_pings.py +++ b/cronitor/tests/test_pings.py @@ -70,6 +70,11 @@ class PingDecoratorTests(unittest.TestCase): def setUp(self): cronitor.api_key = FAKE_API_KEY + # the decorator also captures exceptions; keep them off the network + self._transport = cronitor.ingest.set_transport(cronitor.ingest.Transport(send=MagicMock())) + + def tearDown(self): + cronitor.ingest.set_transport(self._transport) @patch('cronitor.Monitor.ping') def test_ping_wraps_function_success(self, mocked_ping): From c9f14ca74ab044eb36111a3e6f929f23bcf5dbbb Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 29 Oct 2026 21:02:33 +0000 Subject: [PATCH 04/18] Add cronitor.LogHandler for the logging module LogHandler ships logging records as structured log items through the same batching transport. Levels map DEBUG->debug, INFO->info, WARNING->warn, ERROR->error, CRITICAL->fatal, and anything below DEBUG to trace. Records carry logger.name, code.file.path, code.line.number and code.function.name, the %-style template and its arguments, and the cronitor.monitor/cronitor.series binding inside a job. A record with exc_info gets its formatted traceback in exception.stacktrace; no second event is sent. Records from the transport itself are ignored so a failing send cannot feed itself. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01B4Z4DjN96ccpNoVRZuoCxo --- cronitor/__init__.py | 2 +- cronitor/capture.py | 59 +++++++++++++++++ cronitor/tests/test_capture.py | 115 +++++++++++++++++++++++++++++++++ 3 files changed, 175 insertions(+), 1 deletion(-) diff --git a/cronitor/__init__.py b/cronitor/__init__.py index 9a3c3db..4094c63 100644 --- a/cronitor/__init__.py +++ b/cronitor/__init__.py @@ -12,7 +12,7 @@ from .monitor import Monitor, YAML from . import capture, ingest from .ingest import flush -from .capture import capture_exception, capture_message, logger +from .capture import capture_exception, capture_message, logger, LogHandler # the package's own diagnostics; `cronitor.logger` ships structured logs to Cronitor _logger = logging.getLogger(__name__) diff --git a/cronitor/capture.py b/cronitor/capture.py index e722c6f..f48048b 100644 --- a/cronitor/capture.py +++ b/cronitor/capture.py @@ -416,6 +416,65 @@ def _typed(value): return {'value': _truncate(value, MAX_ATTRIBUTE_VALUE_LENGTH), 'type': 'string'} +# logging integration + +_LOGGING_LEVELS = ( + (logging.CRITICAL, 'fatal'), + (logging.ERROR, 'error'), + (logging.WARNING, 'warn'), + (logging.INFO, 'info'), + (logging.DEBUG, 'debug'), +) +# records about sending must not be sent, or a failing transport would feed itself +_INTERNAL_LOGGERS = ('cronitor.ingest', 'cronitor.capture') + + +def _log_level(levelno): + for threshold, name in _LOGGING_LEVELS: + if levelno >= threshold: + return name + return 'trace' + + +class LogHandler(logging.Handler): + """A logging.Handler that ships records to Cronitor as structured logs. + + Records are batched by the background transport. A record with exc_info + carries the formatted traceback in the ``exception.stacktrace`` attribute; + no separate exception event is sent. + """ + + def __init__(self, level=logging.NOTSET): + super(LogHandler, self).__init__(level) + + def emit(self, record): + if ingest.in_worker_thread() or record.name.startswith(_INTERNAL_LOGGERS): + return + try: + attrs = { + 'logger.name': record.name, + 'code.file.path': record.pathname, + 'code.line.number': record.lineno, + 'code.function.name': record.funcName, + } + if record.args and isinstance(record.msg, str): + attrs['sentry.message.template'] = record.msg + params = record.args.items() if isinstance(record.args, dict) else enumerate(record.args) + for key, value in params: + attrs['sentry.message.parameter.{}'.format(key)] = value + if record.exc_info and record.exc_info[0] is not None: + exc_type, exc_value, tb = record.exc_info + stacktrace = ''.join(traceback.format_exception(exc_type, exc_value, tb)) + attrs['exception.type'] = getattr(exc_type, '__name__', _safe_str(exc_type)) + attrs['exception.message'] = _safe_str(exc_value) + # keep the end, where the crash site and the message are + attrs['exception.stacktrace'] = stacktrace[-MAX_ATTRIBUTE_VALUE_LENGTH:] + log = _log_record(_log_level(record.levelno), record.getMessage(), attrs, timestamp=record.created) + ingest.submit_log(log) + except Exception: + self.handleError(record) + + # helpers def _hostname(): diff --git a/cronitor/tests/test_capture.py b/cronitor/tests/test_capture.py index da17179..a3a73af 100644 --- a/cronitor/tests/test_capture.py +++ b/cronitor/tests/test_capture.py @@ -1,7 +1,9 @@ import json +import logging import os import re import socket +import sys import time import unittest from unittest.mock import patch @@ -508,3 +510,116 @@ def test_binding_ends_with_the_job(self): self.assertIsNone(cronitor.capture.current_job()) cronitor.capture_message('after the job') self.assertEqual(self.flushed_events()[-1]['tags'], {}) + + +class LogHandlerTests(CaptureTestCase): + + def setUp(self): + super().setUp() + self.log = logging.getLogger('cronitor.tests.handler') + self.log.propagate = False + self.log.setLevel(1) + self.handler = cronitor.LogHandler() + self.log.addHandler(self.handler) + self.addCleanup(self.log.removeHandler, self.handler) + + def test_level_mapping(self): + self.log.log(5, 'below debug') + self.log.debug('debug line') + self.log.info('info line') + self.log.warning('warning line') + self.log.error('error line') + self.log.critical('critical line') + records = self.flushed_logs() + self.assertEqual([r['level'] for r in records], ['trace', 'debug', 'info', 'warn', 'error', 'fatal']) + self.assertEqual([_attr(r, 'sentry.severity_number')['value'] for r in records], [1, 5, 9, 13, 17, 21]) + self.assertEqual(len(self.send.calls), 1) + + def test_record_attributes(self): + before = time.time() + self.log.info('user %s did %d things', 'bob', 3); line = sys._getframe().f_lineno + record = self.flushed_logs()[0] + self.assertEqual(record['body'], 'user bob did 3 things') + self.assertGreaterEqual(record['timestamp'], before) + self.assertEqual(_attr(record, 'logger.name'), {'value': 'cronitor.tests.handler', 'type': 'string'}) + self.assertEqual(_attr(record, 'code.file.path')['value'], __file__) + self.assertEqual(_attr(record, 'code.line.number'), {'value': line, 'type': 'integer'}) + self.assertEqual(_attr(record, 'code.function.name')['value'], 'test_record_attributes') + self.assertEqual(_attr(record, 'sentry.message.template')['value'], 'user %s did %d things') + self.assertEqual(_attr(record, 'sentry.message.parameter.0'), {'value': 'bob', 'type': 'string'}) + self.assertEqual(_attr(record, 'sentry.message.parameter.1'), {'value': 3, 'type': 'integer'}) + self.assertEqual(_attr(record, 'sentry.sdk.name')['value'], 'cronitor-python') + self.assertEqual(_attr(record, 'server.address')['value'], socket.gethostname()) + + def test_mapping_args(self): + self.log.info('%(user)s logged in', {'user': 'bob'}) + record = self.flushed_logs()[0] + self.assertEqual(record['body'], 'bob logged in') + self.assertEqual(_attr(record, 'sentry.message.parameter.user')['value'], 'bob') + + def test_no_args_records_no_template(self): + self.log.info('100% plain') + record = self.flushed_logs()[0] + self.assertEqual(record['body'], '100% plain') + self.assertNotIn('sentry.message.template', record['attributes']) + + def test_exc_info_adds_stacktrace_and_sends_no_event(self): + try: + raise ValueError('bad input') + except ValueError: + self.log.exception('import failed') + records = self.flushed_logs() + self.assertEqual(self.send.events(), []) + record = records[0] + self.assertEqual(record['level'], 'error') + self.assertEqual(record['body'], 'import failed') + stacktrace = _attr(record, 'exception.stacktrace')['value'] + self.assertTrue(stacktrace.startswith('Traceback (most recent call last):')) + self.assertIn("raise ValueError('bad input')", stacktrace) + self.assertTrue(stacktrace.rstrip().endswith('ValueError: bad input')) + self.assertEqual(_attr(record, 'exception.type')['value'], 'ValueError') + self.assertEqual(_attr(record, 'exception.message')['value'], 'bad input') + + def test_long_stacktrace_keeps_the_end(self): + try: + raise ValueError('x' * 9000 + ' the end') + except ValueError: + self.log.exception('failed') + stacktrace = _attr(self.flushed_logs()[0], 'exception.stacktrace')['value'] + self.assertEqual(len(stacktrace), 8000) + self.assertTrue(stacktrace.rstrip().endswith('the end')) + + def test_handler_level(self): + self.handler.setLevel(logging.WARNING) + self.log.info('dropped') + self.log.warning('kept') + self.assertEqual([r['body'] for r in self.flushed_logs()], ['kept']) + + def test_handler_level_argument(self): + self.assertEqual(cronitor.LogHandler(logging.ERROR).level, logging.ERROR) + self.assertEqual(cronitor.LogHandler().level, logging.NOTSET) + + def test_records_inside_a_job_are_bound(self): + @cronitor.job('handler-job') + def job(): + self.log.info('working') + + with patch('cronitor.Monitor.ping') as ping: + job() + series = str(ping.call_args_list[0].kwargs['series']) + record = self.flushed_logs()[0] + self.assertEqual(_attr(record, 'cronitor.monitor')['value'], 'handler-job') + self.assertEqual(_attr(record, 'cronitor.series')['value'], series) + + def test_ignores_the_transports_own_records(self): + root = logging.getLogger() + root.addHandler(self.handler) + self.addCleanup(root.removeHandler, self.handler) + logging.getLogger('cronitor.ingest').warning('send failed') + ingest._worker_state.active = True + try: + logging.getLogger('urllib3.connectionpool').warning('retrying') + finally: + ingest._worker_state.active = False + self.log.info('kept') + self.assertEqual([r['body'] for r in self.flushed_logs()], ['kept']) From cdc5626b5382b1a9a4aafea97ae5b1b31d582f02 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 29 Oct 2026 21:04:04 +0000 Subject: [PATCH 05/18] Test the default HTTP send path against a loopback server Covers the requests session, gzip body and headers on the wire, a real 429 with Retry-After, and a ping routed through the same ingest_url. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01B4Z4DjN96ccpNoVRZuoCxo --- cronitor/tests/test_ingest.py | 71 +++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) diff --git a/cronitor/tests/test_ingest.py b/cronitor/tests/test_ingest.py index 8a67aae..f81f322 100644 --- a/cronitor/tests/test_ingest.py +++ b/cronitor/tests/test_ingest.py @@ -325,3 +325,74 @@ def test_flush_at_exit(self): stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=30) self.assertEqual(out.returncode, 0, out.stderr) self.assertEqual(out.stdout.decode().strip(), 'SENT 3') + + +class LocalCollectorTests(unittest.TestCase): + """The default requests-based send path against a loopback HTTP server.""" + + def setUp(self): + from http.server import BaseHTTPRequestHandler, HTTPServer + + received = self.received = [] + statuses = self.statuses = [] + + class Handler(BaseHTTPRequestHandler): + def _record(self): + length = int(self.headers.get('Content-Length') or 0) + received.append((self.command, self.path, dict(self.headers), self.rfile.read(length))) + status, headers = statuses.pop(0) if statuses else (200, {}) + self.send_response(status) + for name, value in headers.items(): + self.send_header(name, value) + self.send_header('Content-Length', '2') + self.end_headers() + self.wfile.write(b'{}') + + do_GET = do_POST = _record + + def log_message(self, *args): + pass + + self.server = HTTPServer(('127.0.0.1', 0), Handler) + threading.Thread(target=self.server.serve_forever, daemon=True).start() + self._saved = (cronitor.api_key, cronitor.ingest_url) + cronitor.api_key = FAKE_API_KEY + cronitor.ingest_url = 'http://127.0.0.1:%d' % self.server.server_port + no_proxy = '127.0.0.1,' + os.environ.get('NO_PROXY', os.environ.get('no_proxy', '')) + env = patch.dict(os.environ, {'NO_PROXY': no_proxy, 'no_proxy': no_proxy}) + env.start() + self.addCleanup(env.stop) + + def tearDown(self): + self.server.shutdown() + self.server.server_close() + cronitor.api_key, cronitor.ingest_url = self._saved + + def test_envelopes_and_pings_reach_the_ingest_url(self): + sleeps = [] + transport = ingest.Transport(sleep=sleeps.append) + self.statuses.extend([(200, {}), (429, {'Retry-After': '3'}), (200, {})]) + transport.submit_event(_event('1' * 32)) + transport.submit_event(_event('2' * 32)) + with self.assertLogs('cronitor.ingest', 'WARNING'): + self.assertTrue(transport.flush(5.0)) + transport.submit_log(_record('after 429')) + self.assertTrue(transport.flush(5.0)) + + self.assertEqual(len(self.received), 3) + method, path, headers, body = self.received[0] + self.assertEqual((method, path), ('POST', '/api/envelope')) + self.assertEqual(headers['Content-Type'], 'application/x-sentry-envelope') + self.assertEqual(headers['Content-Encoding'], 'gzip') + self.assertEqual(headers['User-Agent'], 'cronitor-python') + self.assertTrue(headers['X-Sentry-Auth'].startswith('Sentry sentry_key=%s, sentry_version=7,' % FAKE_API_KEY)) + header, items = parse_envelope(body) + self.assertEqual(header['event_id'], '1' * 32) + self.assertEqual(len(sleeps), 1) + self.assertAlmostEqual(sleeps[0], 3, delta=1) + self.assertEqual(parse_envelope(self.received[2][3])[1][0][1]['items'][0]['body'], 'after 429') + + cronitor.Monitor('local-job').ping(state='run') + method, path, _, _ = self.received[3] + self.assertEqual(method, 'GET') + self.assertTrue(path.startswith('/p/%s/local-job?' % FAKE_API_KEY), path) From 20fa49f5c4becea875c64059a163a1e3afa11f8f Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 29 Oct 2026 21:05:05 +0000 Subject: [PATCH 06/18] Document exceptions and logs, bump version to 5.0.0 Adds an "Exceptions and Logs" README section: configuration, capture_exception, capture_message, cronitor.logger, LogHandler, flush, the @job behavior, and the Sentry SDK DSN alternative. Documents CRONITOR_INGEST_URL and CRONITOR_RELEASE. 5.0.0 because @cronitor.job now sends an exception event on failure by default and cronitor.logger is now the log shipper. A test keeps the SDK version reported on the wire equal to setup.py. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01B4Z4DjN96ccpNoVRZuoCxo --- README.md | 70 +++++++++++++++++++++++++++++++++++ cronitor/_version.py | 2 +- cronitor/tests/test_ingest.py | 8 ++++ setup.py | 2 +- 4 files changed, 80 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index a89b506..69241cb 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,7 @@ In this guide: - [Installation](#Installation) - [Monitoring Background Jobs](#monitoring-background-jobs) - [Sending Telemetry Events](#sending-telemetry-events) +- [Exceptions and Logs](#exceptions-and-logs) - [Configuring Monitors](#configuring-monitors) - [Package Configuration & Env Vars](#package-configuration) - [Command Line Usage](#command-line-usage) @@ -124,6 +125,73 @@ monitor.ping( ) ``` +## Exceptions and Logs + +Cronitor can store exception events and structured logs next to your monitors. The SDK captures them natively (no extra dependency) and sends them from a background thread, so your code 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. + +```python +import cronitor + +cronitor.api_key = 'apiKey123' # a telemetry key is enough +cronitor.environment = 'production' # optional +cronitor.release = '2.4.1' # optional, or CRONITOR_RELEASE +``` + +#### Exceptions inside `@cronitor.job` + +When a function decorated with `@cronitor.job` raises, the `fail` ping is sent as before and an exception event with the full stack trace follows, bound to the same monitor and run. Set `cronitor.capture_exceptions = False` to send only the ping. + +Anything captured while the job runs (exceptions, messages, logs) is bound to the monitor and the run automatically. + +#### Capturing exceptions and messages + +```python +try: + import_orders() +except Exception as e: + cronitor.capture_exception(e, monitor='import-orders', tags={'region': 'us-east-1'}, extra={'batch': 42}) + +cronitor.capture_message('Disk 90% full', level='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 +``` + +`capture_exception` and `capture_message` return the event id. 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. + +#### Structured logs + +```python +cronitor.logger.info('Processed {count} orders for {customer}', count=120, customer='acme') +cronitor.logger.warning('Retrying', attempt=3) # also trace, debug, error, fatal +``` + +The body is formatted with `str.format`, and the template and parameters are kept as attributes so you can filter on them. Or ship records from the standard `logging` module: + +```python +import logging + +logging.getLogger().addHandler(cronitor.LogHandler(level=logging.INFO)) +``` + +Logs are batched (100 records or 5 seconds). Queued events and logs are flushed when the process exits; call `cronitor.flush(timeout=2.0)` to flush earlier, for example at the end of a serverless handler. + +> In 5.0 `cronitor.logger` became this log shipper. The package's own diagnostics still use `logging.getLogger('cronitor')`. + +#### Already using the Sentry SDK? + +Cronitor accepts the Sentry wire format, so `sentry_sdk` works by changing the DSN. Bind events to a monitor with a tag: + +```python +import sentry_sdk + +sentry_sdk.init(dsn='https://{telemetry_key}@cronitor.link/{key_id}') +sentry_sdk.set_tag('cronitor.monitor', 'nightly-job') +``` + +`telemetry_key` is a Cronitor API key with telemetry scope and `key_id` is that key's numeric id. + ## Configuring Monitors ### YAML Configuration File @@ -299,6 +367,8 @@ monitor.delete() # destroy the monitor 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`. +Telemetry pings, exceptions and logs are sent to `https://cronitor.link` by default. Set `cronitor.ingest_url` or `CRONITOR_INGEST_URL` to send them elsewhere, for example `http://localhost:9100` in development. `cronitor.release` (`CRONITOR_RELEASE`) is attached to exceptions and logs. + ```python import cronitor diff --git a/cronitor/_version.py b/cronitor/_version.py index 3161916..a0f6658 100644 --- a/cronitor/_version.py +++ b/cronitor/_version.py @@ -1 +1 @@ -__version__ = '4.9.0' +__version__ = '5.0.0' diff --git a/cronitor/tests/test_ingest.py b/cronitor/tests/test_ingest.py index f81f322..fb31132 100644 --- a/cronitor/tests/test_ingest.py +++ b/cronitor/tests/test_ingest.py @@ -70,6 +70,14 @@ def test_format_timestamp(self): self.assertEqual(ingest.format_timestamp(stamp), '2026-10-29T20:00:00.123456Z') +class VersionTests(unittest.TestCase): + + def test_sdk_version_matches_setup_py(self): + with open(os.path.join(REPO_ROOT, 'setup.py')) as f: + version = re.search(r"version='([^']+)'", f.read()).group(1) + self.assertEqual(ingest.SDK_VERSION, version) + + class UrlTests(unittest.TestCase): def setUp(self): diff --git a/setup.py b/setup.py index 49fd9d5..83d89e0 100644 --- a/setup.py +++ b/setup.py @@ -5,7 +5,7 @@ setup( name='cronitor', - version='4.9.0', + version='5.0.0', packages=find_packages(), url='https://github.com/cronitorio/cronitor-python', license='MIT License', From 05f5f0fb4fbd9809fe3904cd12d7469e8807d87f Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 29 Oct 2026 21:07:23 +0000 Subject: [PATCH 07/18] Send strict JSON and report a missing API key once Envelope payloads are now strict JSON: NaN and Infinity in extra or log attributes become strings, circular extra data is cut instead of losing the event, unencodable dict keys are skipped, and lone surrogates are replaced. A missing API key is logged once per transport instead of on every record, which matters with LogHandler on a busy logger. The test envelope parser now rejects NaN like a strict backend would. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01B4Z4DjN96ccpNoVRZuoCxo --- cronitor/capture.py | 3 ++- cronitor/ingest.py | 32 +++++++++++++++++++++++++++++-- cronitor/tests/envelope_parser.py | 6 +++++- cronitor/tests/test_capture.py | 19 ++++++++++++++++++ cronitor/tests/test_ingest.py | 15 +++++++++++++++ 5 files changed, 71 insertions(+), 4 deletions(-) diff --git a/cronitor/capture.py b/cronitor/capture.py index f48048b..d7bf371 100644 --- a/cronitor/capture.py +++ b/cronitor/capture.py @@ -7,6 +7,7 @@ import contextvars import linecache import logging +import math import os import socket import sys @@ -409,7 +410,7 @@ def _typed(value): return {'value': value, 'type': 'boolean'} if isinstance(value, int): return {'value': value, 'type': 'integer'} - if isinstance(value, float): + if isinstance(value, float) and math.isfinite(value): return {'value': value, 'type': 'double'} if not isinstance(value, str): value = _safe_repr(value) diff --git a/cronitor/ingest.py b/cronitor/ingest.py index d726a3f..785580b 100644 --- a/cronitor/ingest.py +++ b/cronitor/ingest.py @@ -9,6 +9,7 @@ import gzip import json import logging +import math import os import queue import threading @@ -90,8 +91,33 @@ def _json_default(value): return '' % type(value).__name__ +def _json_safe(value, depth=0): + """Copy of value with NaN/Infinity as strings and nesting (and so cycles) cut at 10 levels.""" + if isinstance(value, float) and not math.isfinite(value): + return repr(value) + if isinstance(value, (dict, list, tuple)) and depth >= 10: + return _json_default(value) + if isinstance(value, dict): + return {k: _json_safe(v, depth + 1) for k, v in value.items()} + if isinstance(value, (list, tuple)): + return [_json_safe(v, depth + 1) for v in value] + return value + + +def _dumps(obj, allow_nan): + return json.dumps(obj, default=_json_default, ensure_ascii=False, separators=(',', ':'), + skipkeys=True, allow_nan=allow_nan) + + def json_bytes(obj): - return json.dumps(obj, default=_json_default, ensure_ascii=False, separators=(',', ':')).encode('utf-8') + """Strict JSON (no NaN or Infinity) as UTF-8. Values json cannot encode become their repr.""" + try: + text = _dumps(obj, allow_nan=False) + except ValueError: + # a non-finite float or a circular reference somewhere in user data + text = _dumps(_json_safe(obj), allow_nan=False) + # 'replace' turns lone surrogates (undecodable bytes in paths or messages) into '?' + return text.encode('utf-8', 'replace') def serialize_envelope(headers, items): @@ -159,6 +185,7 @@ def __init__(self, send=None, sleep=None, maxsize=MAX_QUEUE_SIZE, self._thread = None self._pid = None self._rate_limited_until = 0.0 + self._reported_missing_key = False self.dropped = 0 # caller side @@ -191,7 +218,8 @@ def flush(self, timeout=2.0): def _api_key(self, api_key): api_key = api_key or cronitor.api_key - if not api_key: + if not api_key and not self._reported_missing_key: + self._reported_missing_key = True logger.error('No API key detected. Set cronitor.api_key to send exceptions and logs.') return api_key diff --git a/cronitor/tests/envelope_parser.py b/cronitor/tests/envelope_parser.py index d49acc2..3406888 100644 --- a/cronitor/tests/envelope_parser.py +++ b/cronitor/tests/envelope_parser.py @@ -9,6 +9,10 @@ import time +def _reject_constant(name): + raise ValueError('not valid JSON: %s' % name) + + def parse_envelope(body, compressed=True): """Parse envelope bytes into (header, [(item_header, payload), ...]). @@ -35,7 +39,7 @@ def parse_envelope(body, compressed=True): if rest[:1] != b'\n': raise AssertionError('payload is not followed by a newline') rest = rest[1:] - items.append((item_header, json.loads(payload.decode('utf-8')))) + items.append((item_header, json.loads(payload.decode('utf-8'), parse_constant=_reject_constant))) return header, items diff --git a/cronitor/tests/test_capture.py b/cronitor/tests/test_capture.py index a3a73af..47e899b 100644 --- a/cronitor/tests/test_capture.py +++ b/cronitor/tests/test_capture.py @@ -266,6 +266,17 @@ def test_tags_extra_and_bindings(self): self.assertEqual(event['extra']['rows'], [1, 2]) self.assertTrue(event['extra']['obj'].startswith(' Date: Thu, 29 Oct 2026 21:15:58 +0000 Subject: [PATCH 08/18] Add cronitor.app to bind events and logs to an app monitor cronitor.app (or CRONITOR_APP) names the app monitor that exception events and log records belong to. A cronitor.app tag or attribute on a single call overrides it. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01B4Z4DjN96ccpNoVRZuoCxo --- README.md | 3 ++- cronitor/__init__.py | 2 ++ cronitor/capture.py | 7 ++++++ cronitor/tests/test_capture.py | 40 ++++++++++++++++++++++++++++++++++ 4 files changed, 51 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 69241cb..e529385 100644 --- a/README.md +++ b/README.md @@ -135,6 +135,7 @@ import cronitor cronitor.api_key = 'apiKey123' # a telemetry key is enough cronitor.environment = 'production' # optional cronitor.release = '2.4.1' # optional, or CRONITOR_RELEASE +cronitor.app = 'billing-service' # optional, or CRONITOR_APP: the app monitor these events belong to ``` #### Exceptions inside `@cronitor.job` @@ -367,7 +368,7 @@ monitor.delete() # destroy the monitor 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`. -Telemetry pings, exceptions and logs are sent to `https://cronitor.link` by default. Set `cronitor.ingest_url` or `CRONITOR_INGEST_URL` to send them elsewhere, for example `http://localhost:9100` in development. `cronitor.release` (`CRONITOR_RELEASE`) is attached to exceptions and logs. +Telemetry pings, exceptions and logs are sent to `https://cronitor.link` by default. Set `cronitor.ingest_url` or `CRONITOR_INGEST_URL` to send them elsewhere, for example `http://localhost:9100` in development. `cronitor.release` (`CRONITOR_RELEASE`) is attached to exceptions and logs. `cronitor.app` (`CRONITOR_APP`) names the app monitor that exceptions and logs belong to; a `cronitor.app` tag or attribute on a single call overrides it. ```python import cronitor diff --git a/cronitor/__init__.py b/cronitor/__init__.py index 4094c63..cb0f00a 100644 --- a/cronitor/__init__.py +++ b/cronitor/__init__.py @@ -31,6 +31,8 @@ ingest_url = os.getenv('CRONITOR_INGEST_URL') or ingest.DEFAULT_INGEST_URL # attached to exception events and logs release = os.getenv('CRONITOR_RELEASE', None) +# app monitor key that exception events and logs belong to, unless a call names another +app = os.getenv('CRONITOR_APP', None) # send an exception event when a function decorated with @cronitor.job raises capture_exceptions = True diff --git a/cronitor/capture.py b/cronitor/capture.py index d7bf371..6c8ad74 100644 --- a/cronitor/capture.py +++ b/cronitor/capture.py @@ -24,6 +24,7 @@ MONITOR_TAG = 'cronitor.monitor' SERIES_TAG = 'cronitor.series' +APP_TAG = 'cronitor.app' MAX_VALUE_LENGTH = 4000 MAX_MESSAGE_LENGTH = 4000 @@ -190,6 +191,9 @@ def _base_event(level, monitor, series, tags, extra, env): bound[MONITOR_TAG] = monitor if series is not None: bound[SERIES_TAG] = series + app = user_tags.get(APP_TAG) or cronitor.app + if app: + bound[APP_TAG] = app event_tags = {} for key, value in list(bound.items()) + list(user_tags.items()): key = _truncate(_safe_str(key), MAX_TAG_KEY_LENGTH) @@ -375,6 +379,7 @@ def _capture_log(level, body, attributes, extra_attributes=None, timestamp=None) def _log_record(level, body, attributes, timestamp=None): user = dict(attributes) monitor, series, env = _binding(user.pop(MONITOR_TAG, None), user.pop(SERIES_TAG, None), None) + app = user.pop(APP_TAG, None) or cronitor.app attrs = { 'sentry.severity_number': LOG_SEVERITY[level], @@ -391,6 +396,8 @@ def _log_record(level, body, attributes, timestamp=None): attrs[MONITOR_TAG] = _safe_str(monitor) if series is not None: attrs[SERIES_TAG] = _safe_str(series) + if app: + attrs[APP_TAG] = _safe_str(app) for key, value in user.items(): key = _safe_str(key) if key in attrs or len(attrs) >= MAX_ATTRIBUTES: diff --git a/cronitor/tests/test_capture.py b/cronitor/tests/test_capture.py index 47e899b..8691697 100644 --- a/cronitor/tests/test_capture.py +++ b/cronitor/tests/test_capture.py @@ -642,3 +642,43 @@ def test_ignores_the_transports_own_records(self): ingest._worker_state.active = False self.log.info('kept') self.assertEqual([r['body'] for r in self.flushed_logs()], ['kept']) + + +class AppSettingTests(CaptureTestCase): + """cronitor.app binds every event and log record to an app monitor unless a call says otherwise.""" + + def setUp(self): + super().setUp() + cronitor.app = None + + def tearDown(self): + cronitor.app = None + super().tearDown() + + def test_default_is_unset(self): + self.assertIsNone(cronitor.app) + cronitor.capture_message('hi') + self.assertNotIn('cronitor.app', self.only_event()['tags']) + + def test_global_app_tags_events(self): + cronitor.app = 'billing-service' + cronitor.capture_message('hi', monitor='nightly-backup') + self.assertEqual(self.only_event()['tags'], + {'cronitor.monitor': 'nightly-backup', 'cronitor.app': 'billing-service'}) + + def test_explicit_tag_overrides_global_app(self): + cronitor.app = 'billing-service' + cronitor.capture_message('hi', tags={'cronitor.app': 'other-app'}) + self.assertEqual(self.only_event()['tags'], {'cronitor.app': 'other-app'}) + + def test_global_app_on_log_records(self): + cronitor.app = 'billing-service' + cronitor.logger.info('hello') + record = self.flushed_logs()[0] + self.assertEqual(_attr(record, 'cronitor.app'), {'value': 'billing-service', 'type': 'string'}) + + def test_log_attribute_overrides_global_app(self): + cronitor.app = 'billing-service' + cronitor.logger.info('hello', **{'cronitor.app': 'other-app'}) + record = self.flushed_logs()[0] + self.assertEqual(_attr(record, 'cronitor.app')['value'], 'other-app') From 6c0270fc3317b2bab4234d59dfad5ecaa3f3bb89 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 29 Oct 2026 21:21:25 +0000 Subject: [PATCH 09/18] Rename the app binding to service The monitor type that owns exceptions and logs is called service. The SDK setting is cronitor.service (CRONITOR_SERVICE) and the tag and log attribute are cronitor.service. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01B4Z4DjN96ccpNoVRZuoCxo --- README.md | 8 +++---- cronitor/__init__.py | 4 ++-- cronitor/capture.py | 14 ++++++------ cronitor/tests/test_capture.py | 40 +++++++++++++++++----------------- 4 files changed, 33 insertions(+), 33 deletions(-) diff --git a/README.md b/README.md index e529385..d278b5f 100644 --- a/README.md +++ b/README.md @@ -135,7 +135,7 @@ import cronitor cronitor.api_key = 'apiKey123' # a telemetry key is enough cronitor.environment = 'production' # optional cronitor.release = '2.4.1' # optional, or CRONITOR_RELEASE -cronitor.app = 'billing-service' # optional, or CRONITOR_APP: the app monitor these events belong to +cronitor.service = 'billing-api' # optional, or CRONITOR_SERVICE: the service monitor these events belong to ``` #### Exceptions inside `@cronitor.job` @@ -210,7 +210,7 @@ cronitor.read_config('./cronitor.yaml') # parse the yaml file of monitors cronitor.validate_config() # send monitors to Cronitor for configuration validation -cronitor.apply_config() # sync the monitors from the config file to Cronitor +cronitor.servicely_config() # sync the monitors from the config file to Cronitor cronitor.generate_config() # generate a new config file from the Cronitor API ``` @@ -221,7 +221,7 @@ The timeout value for validate_config, apply_config and generate_config is 10 se import cronitor cronitor.timeout = 30 -cronitor.apply_config() +cronitor.servicely_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). @@ -368,7 +368,7 @@ monitor.delete() # destroy the monitor 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`. -Telemetry pings, exceptions and logs are sent to `https://cronitor.link` by default. Set `cronitor.ingest_url` or `CRONITOR_INGEST_URL` to send them elsewhere, for example `http://localhost:9100` in development. `cronitor.release` (`CRONITOR_RELEASE`) is attached to exceptions and logs. `cronitor.app` (`CRONITOR_APP`) names the app monitor that exceptions and logs belong to; a `cronitor.app` tag or attribute on a single call overrides it. +Telemetry pings, exceptions and logs are sent to `https://cronitor.link` by default. Set `cronitor.ingest_url` or `CRONITOR_INGEST_URL` to send them elsewhere, for example `http://localhost:9100` in development. `cronitor.release` (`CRONITOR_RELEASE`) is attached to exceptions and logs. `cronitor.service` (`CRONITOR_SERVICE`) names the service monitor that exceptions and logs belong to; a `cronitor.service` tag or attribute on a single call overrides it. ```python import cronitor diff --git a/cronitor/__init__.py b/cronitor/__init__.py index cb0f00a..6a3db4c 100644 --- a/cronitor/__init__.py +++ b/cronitor/__init__.py @@ -31,8 +31,8 @@ ingest_url = os.getenv('CRONITOR_INGEST_URL') or ingest.DEFAULT_INGEST_URL # attached to exception events and logs release = os.getenv('CRONITOR_RELEASE', None) -# app monitor key that exception events and logs belong to, unless a call names another -app = os.getenv('CRONITOR_APP', None) +# service monitor key that exception events and logs belong to, unless a call names another +service = os.getenv('CRONITOR_SERVICE', None) # send an exception event when a function decorated with @cronitor.job raises capture_exceptions = True diff --git a/cronitor/capture.py b/cronitor/capture.py index 6c8ad74..628a750 100644 --- a/cronitor/capture.py +++ b/cronitor/capture.py @@ -24,7 +24,7 @@ MONITOR_TAG = 'cronitor.monitor' SERIES_TAG = 'cronitor.series' -APP_TAG = 'cronitor.app' +SERVICE_TAG = 'cronitor.service' MAX_VALUE_LENGTH = 4000 MAX_MESSAGE_LENGTH = 4000 @@ -191,9 +191,9 @@ def _base_event(level, monitor, series, tags, extra, env): bound[MONITOR_TAG] = monitor if series is not None: bound[SERIES_TAG] = series - app = user_tags.get(APP_TAG) or cronitor.app - if app: - bound[APP_TAG] = app + service = user_tags.get(SERVICE_TAG) or cronitor.service + if service: + bound[SERVICE_TAG] = service event_tags = {} for key, value in list(bound.items()) + list(user_tags.items()): key = _truncate(_safe_str(key), MAX_TAG_KEY_LENGTH) @@ -379,7 +379,7 @@ def _capture_log(level, body, attributes, extra_attributes=None, timestamp=None) def _log_record(level, body, attributes, timestamp=None): user = dict(attributes) monitor, series, env = _binding(user.pop(MONITOR_TAG, None), user.pop(SERIES_TAG, None), None) - app = user.pop(APP_TAG, None) or cronitor.app + service = user.pop(SERVICE_TAG, None) or cronitor.service attrs = { 'sentry.severity_number': LOG_SEVERITY[level], @@ -396,8 +396,8 @@ def _log_record(level, body, attributes, timestamp=None): attrs[MONITOR_TAG] = _safe_str(monitor) if series is not None: attrs[SERIES_TAG] = _safe_str(series) - if app: - attrs[APP_TAG] = _safe_str(app) + if service: + attrs[SERVICE_TAG] = _safe_str(service) for key, value in user.items(): key = _safe_str(key) if key in attrs or len(attrs) >= MAX_ATTRIBUTES: diff --git a/cronitor/tests/test_capture.py b/cronitor/tests/test_capture.py index 8691697..4b044bc 100644 --- a/cronitor/tests/test_capture.py +++ b/cronitor/tests/test_capture.py @@ -644,41 +644,41 @@ def test_ignores_the_transports_own_records(self): self.assertEqual([r['body'] for r in self.flushed_logs()], ['kept']) -class AppSettingTests(CaptureTestCase): - """cronitor.app binds every event and log record to an app monitor unless a call says otherwise.""" +class ServiceSettingTests(CaptureTestCase): + """cronitor.service binds every event and log record to a service monitor unless a call says otherwise.""" def setUp(self): super().setUp() - cronitor.app = None + cronitor.service = None def tearDown(self): - cronitor.app = None + cronitor.service = None super().tearDown() def test_default_is_unset(self): - self.assertIsNone(cronitor.app) + self.assertIsNone(cronitor.service) cronitor.capture_message('hi') - self.assertNotIn('cronitor.app', self.only_event()['tags']) + self.assertNotIn('cronitor.service', self.only_event()['tags']) - def test_global_app_tags_events(self): - cronitor.app = 'billing-service' + def test_global_service_tags_events(self): + cronitor.service = 'billing-api' cronitor.capture_message('hi', monitor='nightly-backup') self.assertEqual(self.only_event()['tags'], - {'cronitor.monitor': 'nightly-backup', 'cronitor.app': 'billing-service'}) + {'cronitor.monitor': 'nightly-backup', 'cronitor.service': 'billing-api'}) - def test_explicit_tag_overrides_global_app(self): - cronitor.app = 'billing-service' - cronitor.capture_message('hi', tags={'cronitor.app': 'other-app'}) - self.assertEqual(self.only_event()['tags'], {'cronitor.app': 'other-app'}) + def test_explicit_tag_overrides_global_service(self): + cronitor.service = 'billing-api' + cronitor.capture_message('hi', tags={'cronitor.service': 'other-service'}) + self.assertEqual(self.only_event()['tags'], {'cronitor.service': 'other-service'}) - def test_global_app_on_log_records(self): - cronitor.app = 'billing-service' + def test_global_service_on_log_records(self): + cronitor.service = 'billing-api' cronitor.logger.info('hello') record = self.flushed_logs()[0] - self.assertEqual(_attr(record, 'cronitor.app'), {'value': 'billing-service', 'type': 'string'}) + self.assertEqual(_attr(record, 'cronitor.service'), {'value': 'billing-api', 'type': 'string'}) - def test_log_attribute_overrides_global_app(self): - cronitor.app = 'billing-service' - cronitor.logger.info('hello', **{'cronitor.app': 'other-app'}) + def test_log_attribute_overrides_global_service(self): + cronitor.service = 'billing-api' + cronitor.logger.info('hello', **{'cronitor.service': 'other-service'}) record = self.flushed_logs()[0] - self.assertEqual(_attr(record, 'cronitor.app')['value'], 'other-app') + self.assertEqual(_attr(record, 'cronitor.service')['value'], 'other-service') From f32175e7f4470ea0dd5f1c27b9c78260d2e73abe Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 29 Oct 2026 22:02:45 +0000 Subject: [PATCH 10/18] Keep running the job when a ping fails, and fix the README DSN A telemetry outage used to raise the ping's ConnectionError into the decorated function before it ran. Pings are now best effort and logged. The README points Sentry SDK users at a service monitor's dsn instead of an API key id, and restores apply_config() in two examples. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01B4Z4DjN96ccpNoVRZuoCxo --- README.md | 8 ++++---- cronitor/__init__.py | 15 ++++++++++++--- cronitor/tests/test_capture.py | 15 +++++++++++++++ 3 files changed, 31 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index d278b5f..839d5a8 100644 --- a/README.md +++ b/README.md @@ -187,11 +187,11 @@ Cronitor accepts the Sentry wire format, so `sentry_sdk` works by changing the D ```python import sentry_sdk -sentry_sdk.init(dsn='https://{telemetry_key}@cronitor.link/{key_id}') +sentry_sdk.init(dsn='https://{telemetry_key}@cronitor.link/{service_monitor_id}') sentry_sdk.set_tag('cronitor.monitor', 'nightly-job') ``` -`telemetry_key` is a Cronitor API key with telemetry scope and `key_id` is that key's numeric id. +The DSN is the `dsn` field of a service monitor: create one with the Monitors API (`type: "service"`) or `Monitor.put(key='billing-api', type='service')` and read `monitor.data.dsn`. Its path is the monitor's numeric id. ## Configuring Monitors @@ -210,7 +210,7 @@ cronitor.read_config('./cronitor.yaml') # parse the yaml file of monitors cronitor.validate_config() # send monitors to Cronitor for configuration validation -cronitor.servicely_config() # sync the monitors from the config file to Cronitor +cronitor.apply_config() # sync the monitors from the config file to Cronitor cronitor.generate_config() # generate a new config file from the Cronitor API ``` @@ -221,7 +221,7 @@ The timeout value for validate_config, apply_config and generate_config is 10 se import cronitor cronitor.timeout = 30 -cronitor.servicely_config() +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). diff --git a/cronitor/__init__.py b/cronitor/__init__.py index 6a3db4c..75e1bf0 100644 --- a/cronitor/__init__.py +++ b/cronitor/__init__.py @@ -67,6 +67,15 @@ class State(object): COMPLETE = 'complete' FAIL = 'fail' +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: # noqa: BLE001 - any transport error is swallowed on purpose + _logger.warning('Cronitor could not send the %s ping for %s: %s', params.get('state'), monitor.key, e) + return None + + # 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): @@ -81,7 +90,7 @@ 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) # exceptions and logs captured while the function runs are bound to this run job_env = env or this.environment token = capture.bind_job(key, start, job_env) @@ -89,7 +98,7 @@ def wrapped(*args, **kwargs): 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) if this.capture_exceptions: capture._capture_exception(e, monitor=key, series=start, env=job_env, mechanism='cronitor.job', handled=False) @@ -99,7 +108,7 @@ def wrapped(*args, **kwargs): 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 diff --git a/cronitor/tests/test_capture.py b/cronitor/tests/test_capture.py index 4b044bc..ca92721 100644 --- a/cronitor/tests/test_capture.py +++ b/cronitor/tests/test_capture.py @@ -6,6 +6,8 @@ import sys import time import unittest + +import requests from unittest.mock import patch import cronitor @@ -462,6 +464,19 @@ def _ping_calls(self, state): def test_success_sends_no_event(self): self.assertEqual(_successful_job(), 'done') + + def test_ping_failures_never_reach_the_job(self): + # A telemetry outage must not stop the job: pings are best effort. + self.ping.side_effect = requests.ConnectionError('telemetry host down') + self.assertEqual(_successful_job(), 'done') + self.assertEqual(len(self._ping_calls('run')), 1) + self.assertEqual(len(self._ping_calls('complete')), 1) + + def test_ping_failure_still_captures_the_exception(self): + self.ping.side_effect = requests.ConnectionError('telemetry host down') + with self.assertRaises(KeyError): + _failing_job() + self.assertEqual(self.only_event()['exception']['values'][-1]['type'], 'KeyError') self.assertEqual(len(self._ping_calls('complete')), 1) self.assertEqual(self.flushed_events(), []) From 31e7622715ac7df436124c569c97eed3a3b4d7a6 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 29 Oct 2026 22:06:04 +0000 Subject: [PATCH 11/18] Restore the success-path assertions in the job decorator tests Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01B4Z4DjN96ccpNoVRZuoCxo --- cronitor/tests/test_capture.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/cronitor/tests/test_capture.py b/cronitor/tests/test_capture.py index ca92721..8b85060 100644 --- a/cronitor/tests/test_capture.py +++ b/cronitor/tests/test_capture.py @@ -464,6 +464,8 @@ def _ping_calls(self, state): def test_success_sends_no_event(self): self.assertEqual(_successful_job(), 'done') + self.assertEqual(len(self._ping_calls('complete')), 1) + self.assertEqual(self.flushed_events(), []) def test_ping_failures_never_reach_the_job(self): # A telemetry outage must not stop the job: pings are best effort. @@ -474,11 +476,9 @@ def test_ping_failures_never_reach_the_job(self): def test_ping_failure_still_captures_the_exception(self): self.ping.side_effect = requests.ConnectionError('telemetry host down') - with self.assertRaises(KeyError): + with self.assertRaises(ValueError): _failing_job() - self.assertEqual(self.only_event()['exception']['values'][-1]['type'], 'KeyError') - self.assertEqual(len(self._ping_calls('complete')), 1) - self.assertEqual(self.flushed_events(), []) + self.assertEqual(self.only_event()['exception']['values'][-1]['type'], 'ValueError') def test_failure_sends_fail_ping_then_unhandled_event_with_same_series(self): order = [] From 18410f12cc5cc3d807ab83270aac9226381a6afe Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 29 Oct 2026 22:14:10 +0000 Subject: [PATCH 12/18] Drop the parent's HTTP session in a forked child A child that inherited the transport reused the parent's keep-alive session, so both processes wrote to the same TLS socket, and a pool lock held by a parent thread at fork time could deadlock the child. When the pid changes the session and the rate limit window are reset along with the queue and the worker thread. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01B4Z4DjN96ccpNoVRZuoCxo --- cronitor/ingest.py | 5 +++++ cronitor/tests/test_ingest.py | 18 ++++++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/cronitor/ingest.py b/cronitor/ingest.py index 785580b..7a81322 100644 --- a/cronitor/ingest.py +++ b/cronitor/ingest.py @@ -247,6 +247,11 @@ def _ensure_worker(self): if self._pid != pid or self._queue is None: # first use, or a forked child: items queued by the parent are not ours to send self._queue = queue.Queue(maxsize=self._maxsize) + if self._pid != pid: + # nor is its keep-alive session: the sockets are shared with the parent, and a + # connection pool lock held by a parent thread at fork time is never released + self._session = None + self._rate_limited_until = 0.0 thread = threading.Thread(target=self._run, args=(self._queue,), name='cronitor-ingest') thread.daemon = True thread.start() diff --git a/cronitor/tests/test_ingest.py b/cronitor/tests/test_ingest.py index 84e5085..96e144c 100644 --- a/cronitor/tests/test_ingest.py +++ b/cronitor/tests/test_ingest.py @@ -5,6 +5,7 @@ import subprocess import sys import threading +import time import unittest from unittest.mock import patch @@ -314,6 +315,23 @@ def test_new_worker_after_fork(self): self.assertIsNot(self.transport._thread, first_thread) self.assertEqual(len(self.send.calls), 2) + def test_forked_child_does_not_reuse_the_parents_session(self): + # the parent's keep-alive session shares its TLS sockets and pool locks with the child + self.transport.submit_event(_event('1' * 32)) + self.transport.flush(2.0) + first_thread, first_queue = self.transport._thread, self.transport._queue + parent_session = object() + self.transport._session = parent_session + self.transport._rate_limited_until = time.monotonic() + 30 + self.transport._pid = os.getpid() + 100000 # as if the worker were started by a parent process + self.transport._ensure_worker() + self.assertIsNone(self.transport._session) + self.assertEqual(self.transport._rate_limited_until, 0.0) + self.assertIsNot(self.transport._queue, first_queue) + self.assertIsNot(self.transport._thread, first_thread) + self.assertTrue(self.transport._thread.is_alive()) + self.assertEqual(self.transport._pid, os.getpid()) + class ModuleTransportTests(unittest.TestCase): From 480934967c73e0d9daf3dd2a5ab6513296219d6f Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 29 Oct 2026 22:16:45 +0000 Subject: [PATCH 13/18] Keep stdlib logger calls working on cronitor.logger Before 5.0 cronitor.logger was logging.getLogger('cronitor'), so code like cronitor.logger.info('x %s', 1) now raised TypeError. The logger takes %-style arguments (falling back to the raw body when they do not format), and adds warn, critical, exception (an error log carrying the handled exception's type, message and stack trace) and log(level, ...) for stdlib level numbers and names. Configuration calls still pass through to the stdlib logger. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01B4Z4DjN96ccpNoVRZuoCxo --- README.md | 2 +- cronitor/capture.py | 103 ++++++++++++++++++++++++++------- cronitor/tests/test_capture.py | 81 +++++++++++++++++++++++++- 3 files changed, 162 insertions(+), 24 deletions(-) diff --git a/README.md b/README.md index 839d5a8..5b14924 100644 --- a/README.md +++ b/README.md @@ -178,7 +178,7 @@ logging.getLogger().addHandler(cronitor.LogHandler(level=logging.INFO)) Logs are batched (100 records or 5 seconds). Queued events and logs are flushed when the process exits; call `cronitor.flush(timeout=2.0)` to flush earlier, for example at the end of a serverless handler. -> In 5.0 `cronitor.logger` became this log shipper. The package's own diagnostics still use `logging.getLogger('cronitor')`. +> In 5.0 `cronitor.logger` became this log shipper. Calls written for the stdlib logger it used to be keep working: %-style arguments (`cronitor.logger.info('Synced %s rows', 120)`), `warn`, `critical`, `exception` (an error log with the exception being handled: `exception.type`, `exception.message` and `exception.stacktrace`) and `log(level, ...)` with a stdlib level number or name. Configuration calls such as `setLevel` still reach `logging.getLogger('cronitor')`, which the package's own diagnostics use. #### Already using the Sentry SDK? diff --git a/cronitor/capture.py b/cronitor/capture.py index 628a750..d1086f3 100644 --- a/cronitor/capture.py +++ b/cronitor/capture.py @@ -16,6 +16,7 @@ import traceback import uuid from collections import namedtuple +from collections.abc import Mapping import cronitor from . import ingest @@ -83,28 +84,42 @@ class Logger(object): ``cronitor.logger.info('processed {count} rows', count=5)`` formats the body with ``str.format`` and records the template and parameters as attributes. + + Before 5.0 ``cronitor.logger`` was ``logging.getLogger('cronitor')``, so calls + written for it keep working: %-style arguments (``info('x %s', 1)``), ``warn``, + ``critical``, ``exception`` and ``log(level, ...)``. """ - def trace(self, body, **attributes): - _capture_log('trace', body, attributes) + def trace(self, body, *args, **attributes): + _capture_log('trace', body, attributes, args=args) + + def debug(self, body, *args, **attributes): + _capture_log('debug', body, attributes, args=args) + + def info(self, body, *args, **attributes): + _capture_log('info', body, attributes, args=args) - def debug(self, body, **attributes): - _capture_log('debug', body, attributes) + def warning(self, body, *args, **attributes): + _capture_log('warn', body, attributes, args=args) - def info(self, body, **attributes): - _capture_log('info', body, attributes) + def error(self, body, *args, **attributes): + _capture_log('error', body, attributes, args=args) - def warning(self, body, **attributes): - _capture_log('warn', body, attributes) + def fatal(self, body, *args, **attributes): + _capture_log('fatal', body, attributes, args=args) - def error(self, body, **attributes): - _capture_log('error', body, attributes) + warn = warning + critical = fatal - def fatal(self, body, **attributes): - _capture_log('fatal', body, attributes) + def exception(self, body, *args, **attributes): + """An error log carrying the exception being handled, like ``logging.Logger.exception``.""" + _capture_log('error', body, attributes, args=args, exc_info=sys.exc_info()) - # Before 5.0 `cronitor.logger` was logging.getLogger('cronitor'). Keep its - # configuration methods working so existing setup code does not break. + def log(self, level, body, *args, **attributes): + """Log at a stdlib level number (``logging.INFO``) or a level name (``'info'``, ``'WARNING'``).""" + _capture_log(level, body, attributes, args=args) + + # Keep the stdlib logger's configuration methods working so existing setup code does not break. _STDLIB_CONFIG = frozenset(['setLevel', 'getEffectiveLevel', 'isEnabledFor', 'addHandler', 'removeHandler', 'hasHandlers', 'addFilter', 'removeFilter', 'handlers', 'filters', 'level', 'name', 'propagate', 'disabled']) @@ -348,14 +363,18 @@ def _in_app(abs_path): # logs -def _capture_log(level, body, attributes, extra_attributes=None, timestamp=None): +def _capture_log(level, body, attributes, args=(), exc_info=None, extra_attributes=None, timestamp=None): try: + level = _level_name(level) template = _safe_str(body) params = dict(attributes) plain = params.pop('attributes') if isinstance(params.get('attributes'), dict) else {} attrs = {} text = template - if params and '{' in template: + if args: + text, attrs = _percent_format(template, args) + attrs.update(params) + elif params and '{' in template: try: text = template.format(**params) attrs['sentry.message.template'] = template @@ -367,6 +386,8 @@ def _capture_log(level, body, attributes, extra_attributes=None, timestamp=None) else: attrs.update(params) attrs.update(plain) + if exc_info is not None and exc_info[0] is not None: + attrs.update(_exception_attributes(*exc_info)) if extra_attributes: attrs.update(extra_attributes) record = _log_record(level, text, attrs, timestamp) @@ -376,6 +397,49 @@ def _capture_log(level, body, attributes, extra_attributes=None, timestamp=None) return False +def _percent_format(template, args): + """Format like the stdlib's LogRecord.getMessage(), keeping the template on error. + + Returns (text, attributes): the parameters, and the template when it formatted. + """ + if len(args) == 1 and isinstance(args[0], Mapping) and args[0]: + args = args[0] + params = args.items() if isinstance(args, Mapping) else enumerate(args) + attrs = {'sentry.message.parameter.{}'.format(key): value for key, value in params} + try: + text = template % args + except Exception: + return template, attrs + attrs['sentry.message.template'] = template + return text, attrs + + +def _exception_attributes(exc_type, exc_value, tb): + stacktrace = ''.join(traceback.format_exception(exc_type, exc_value, tb)) + return { + 'exception.type': getattr(exc_type, '__name__', _safe_str(exc_type)), + 'exception.message': _safe_str(exc_value), + # keep the end, where the crash site and the message are + 'exception.stacktrace': stacktrace[-MAX_ATTRIBUTE_VALUE_LENGTH:], + } + + +_LOG_LEVEL_NAMES = {'trace': 'trace', 'debug': 'debug', 'info': 'info', 'warn': 'warn', 'warning': 'warn', + 'error': 'error', 'fatal': 'fatal', 'critical': 'fatal'} + + +def _level_name(level): + """A log level from a name (``'info'``, ``'WARNING'``) or a stdlib level number (``logging.INFO``).""" + if isinstance(level, int): + return _log_level(level) + name = _safe_str(level).lower() + if name in _LOG_LEVEL_NAMES: + return _LOG_LEVEL_NAMES[name] + # a custom level registered with logging.addLevelName + number = logging.getLevelName(name.upper()) + return _log_level(number) if isinstance(number, int) else 'info' + + def _log_record(level, body, attributes, timestamp=None): user = dict(attributes) monitor, series, env = _binding(user.pop(MONITOR_TAG, None), user.pop(SERIES_TAG, None), None) @@ -471,12 +535,7 @@ def emit(self, record): for key, value in params: attrs['sentry.message.parameter.{}'.format(key)] = value if record.exc_info and record.exc_info[0] is not None: - exc_type, exc_value, tb = record.exc_info - stacktrace = ''.join(traceback.format_exception(exc_type, exc_value, tb)) - attrs['exception.type'] = getattr(exc_type, '__name__', _safe_str(exc_type)) - attrs['exception.message'] = _safe_str(exc_value) - # keep the end, where the crash site and the message are - attrs['exception.stacktrace'] = stacktrace[-MAX_ATTRIBUTE_VALUE_LENGTH:] + attrs.update(_exception_attributes(*record.exc_info)) log = _log_record(_log_level(record.levelno), record.getMessage(), attrs, timestamp=record.created) ingest.submit_log(log) except Exception: diff --git a/cronitor/tests/test_capture.py b/cronitor/tests/test_capture.py index 8b85060..b0005ef 100644 --- a/cronitor/tests/test_capture.py +++ b/cronitor/tests/test_capture.py @@ -419,7 +419,86 @@ def test_stdlib_configuration_calls_still_work(self): finally: stdlib.setLevel(level) with self.assertRaises(AttributeError): - cronitor.logger.exception + cronitor.logger.no_such_method + + +class StdlibLoggerCompatibilityTests(CaptureTestCase): + """Calls written for logging.getLogger('cronitor'), which cronitor.logger was before 5.0.""" + + def test_percent_args_are_formatted(self): + cronitor.logger.info('x %s', 1) + cronitor.logger.info('user %s did %d things', 'bob', 3) + first, second = self.flushed_logs() + self.assertEqual(first['body'], 'x 1') + self.assertEqual(second['body'], 'user bob did 3 things') + self.assertEqual(_attr(second, 'sentry.message.template')['value'], 'user %s did %d things') + self.assertEqual(_attr(second, 'sentry.message.parameter.0'), {'value': 'bob', 'type': 'string'}) + self.assertEqual(_attr(second, 'sentry.message.parameter.1'), {'value': 3, 'type': 'integer'}) + + def test_mapping_arg_and_attributes(self): + cronitor.logger.info('%(user)s logged in', {'user': 'bob'}, team='core') + record = self.flushed_logs()[0] + self.assertEqual(record['body'], 'bob logged in') + self.assertEqual(_attr(record, 'sentry.message.parameter.user')['value'], 'bob') + self.assertEqual(_attr(record, 'team')['value'], 'core') + + def test_bad_format_keeps_the_body_and_never_raises(self): + class Unprintable(object): + def __str__(self): + raise RuntimeError('no str') + + cronitor.logger.info('two %s %s', 1) + cronitor.logger.info('number %d', 'not a number') + cronitor.logger.info('object %s', Unprintable()) + self.assertEqual([r['body'] for r in self.flushed_logs()], + ['two %s %s', 'number %d', 'object %s']) + + def test_warn_and_critical_aliases(self): + cronitor.logger.warn('careful %s', 'now') + cronitor.logger.critical('down') + warn, critical = self.flushed_logs() + self.assertEqual((warn['level'], warn['body']), ('warn', 'careful now')) + self.assertEqual(critical['level'], 'fatal') + + def test_exception_adds_the_handled_exception(self): + try: + raise ValueError('bad input') + except ValueError: + cronitor.logger.exception('import %s failed', 'orders', batch=4) + record = self.flushed_logs()[0] + self.assertEqual(self.send.events(), []) + self.assertEqual((record['level'], record['body']), ('error', 'import orders failed')) + self.assertEqual(_attr(record, 'exception.type')['value'], 'ValueError') + self.assertEqual(_attr(record, 'exception.message')['value'], 'bad input') + stacktrace = _attr(record, 'exception.stacktrace')['value'] + self.assertTrue(stacktrace.startswith('Traceback (most recent call last):')) + self.assertTrue(stacktrace.rstrip().endswith('ValueError: bad input')) + self.assertEqual(_attr(record, 'batch')['value'], 4) + + def test_exception_outside_an_except_block_is_an_error_log(self): + cronitor.logger.exception('nothing raised') + record = self.flushed_logs()[0] + self.assertEqual(record['level'], 'error') + self.assertNotIn('exception.type', record['attributes']) + + def test_log_with_stdlib_levels_and_names(self): + cronitor.logger.log(logging.WARNING, 'w %s', 1) + cronitor.logger.log(logging.CRITICAL, 'c') + cronitor.logger.log(5, 'below debug') + cronitor.logger.log('ERROR', 'e') + cronitor.logger.log('warning', 'w') + cronitor.logger.log('critical', 'c') + cronitor.logger.log('trace', 't') + cronitor.logger.log('no such level', 'unknown') + records = self.flushed_logs() + self.assertEqual([r['level'] for r in records], + ['warn', 'fatal', 'trace', 'error', 'warn', 'fatal', 'trace', 'info']) + self.assertEqual(records[0]['body'], 'w 1') + + def test_log_with_a_registered_custom_level(self): + logging.addLevelName(45, 'CRONITOR_TEST_SEVERE') + cronitor.logger.log('cronitor_test_severe', 'custom') + self.assertEqual(self.flushed_logs()[0]['level'], 'error') def test_logs_are_batched_into_one_envelope(self): for i in range(3): From 46e474fe5642bed107d56b470c416139551aedf1 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 29 Oct 2026 22:18:25 +0000 Subject: [PATCH 14/18] Trim exception events to stay under the server's size limit The server drops event items over 1 MB, and a deep exception chain with source context or a large extra could exceed it. An event over 900 KB now loses every frame's source context, then extra, then all but the last 20 frames of each exception, stopping as soon as it fits, and extra['_trimmed'] records what was dropped. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01B4Z4DjN96ccpNoVRZuoCxo --- cronitor/ingest.py | 85 +++++++++++++++++++++++++++++++++- cronitor/tests/test_capture.py | 47 +++++++++++++++++++ cronitor/tests/test_ingest.py | 67 +++++++++++++++++++++++++++ 3 files changed, 198 insertions(+), 1 deletion(-) diff --git a/cronitor/ingest.py b/cronitor/ingest.py index 7a81322..1c9a220 100644 --- a/cronitor/ingest.py +++ b/cronitor/ingest.py @@ -32,6 +32,9 @@ SEND_RETRIES = 1 MAX_RETRY_AFTER = 60.0 ATEXIT_FLUSH_TIMEOUT = 2.0 +# the server drops event items over 1 MB; oversized events are trimmed to this +MAX_EVENT_BYTES = 900 * 1024 +TRIMMED_FRAMES = 20 EVENT_CONTENT_TYPE = 'application/json' LOG_CONTENT_TYPE = 'application/vnd.sentry.items.log+json' @@ -132,6 +135,86 @@ def serialize_envelope(headers, items): return b''.join(parts) +def event_bytes(event): + """The event as JSON bytes, trimmed to at most MAX_EVENT_BYTES when possible. + + An oversized event loses, until it fits: every frame's source context, then + ``extra``, then all but the last 20 frames of each exception. + ``extra['_trimmed']`` says what was dropped. The caller's dict is not changed. + """ + payload = json_bytes(event) + if len(payload) <= MAX_EVENT_BYTES: + return payload + try: + event = dict(event) + dropped = [] + for note, trim in _EVENT_TRIMS: + if not trim(event): + continue + dropped.append(note) + extra = event.get('extra') + extra = dict(extra) if isinstance(extra, dict) else {} + extra['_trimmed'] = '%s: event over %d KB' % ('; '.join(dropped), MAX_EVENT_BYTES // 1024) + event['extra'] = extra + payload = json_bytes(event) + if len(payload) <= MAX_EVENT_BYTES: + break + except Exception as e: + logger.warning('Cronitor could not trim an oversized event: %s', e) + return payload + + +def _own_frames(event): + """Give event its own copies of the exception values and frames, and return the frame lists.""" + exception = event.get('exception') or {} + values, frame_lists = [], [] + for value in exception.get('values') or []: + stacktrace = value.get('stacktrace') or {} + if stacktrace.get('frames'): + frames = [dict(frame) for frame in stacktrace['frames']] + value = dict(value, stacktrace=dict(stacktrace, frames=frames)) + frame_lists.append(frames) + values.append(value) + if values: + event['exception'] = dict(exception, values=values) + return frame_lists + + +def _drop_source_context(event): + dropped = False + for frames in _own_frames(event): + for frame in frames: + for key in ('pre_context', 'post_context'): + if key in frame: + del frame[key] + dropped = True + return dropped + + +def _drop_extra(event): + extra = event.get('extra') + if not isinstance(extra, dict) or all(key == '_trimmed' for key in extra): + return False + event['extra'] = {} + return True + + +def _keep_last_frames(event): + cut = False + for frames in _own_frames(event): + if len(frames) > TRIMMED_FRAMES: + del frames[:-TRIMMED_FRAMES] + cut = True + return cut + + +_EVENT_TRIMS = ( + ('source context dropped', _drop_source_context), + ('extra dropped', _drop_extra), + ('frames cut to the last %d per exception' % TRIMMED_FRAMES, _keep_last_frames), +) + + def event_envelope(payload, event_id, sent_at=None): headers = {'event_id': event_id, 'sent_at': format_timestamp(sent_at), 'sdk': sdk_info()} item = {'type': 'event', 'content_type': EVENT_CONTENT_TYPE} @@ -195,7 +278,7 @@ def submit_event(self, event, api_key=None): api_key = self._api_key(api_key) if not api_key: return False - return self._put(('event', envelope_url(), api_key, event['event_id'], json_bytes(event))) + return self._put(('event', envelope_url(), api_key, event['event_id'], event_bytes(event))) def submit_log(self, record, api_key=None): """Queue one log record dict. Returns False when it was not queued.""" diff --git a/cronitor/tests/test_capture.py b/cronitor/tests/test_capture.py index b0005ef..a3f06e2 100644 --- a/cronitor/tests/test_capture.py +++ b/cronitor/tests/test_capture.py @@ -236,6 +236,53 @@ def test_no_api_key_sends_nothing(self): self.assertIsNone(cronitor.capture_exception(e)) self.assertEqual(self.flushed_events(), []) + def test_huge_extra_is_dropped_to_fit_the_size_limit(self): + try: + raise ValueError('x') + except ValueError as e: + event_id = cronitor.capture_exception(e, extra={'blob': 'x' * 2000000}) + self.assertRegex(event_id, HEX32) + event = self.only_event() + self.assertEqual(event['extra'], {'_trimmed': 'source context dropped; extra dropped: event over 900 KB'}) + frame = event['exception']['values'][0]['stacktrace']['frames'][-1] + self.assertEqual(frame['context_line'].strip(), "raise ValueError('x')") + self.assertNotIn('pre_context', frame) + + def test_many_chained_frames_are_trimmed_to_fit(self): + def recurse(n, i): + if n == 0: + raise ValueError('bottom %d' % i) + return recurse(n - 1, i) + + def chain(i): + try: + recurse(150, i) + except ValueError as e: + if i == 0: + raise + try: + chain(i - 1) + except ValueError as cause: + raise e from cause + + try: + chain(9) + except ValueError as e: + # a real chain of short source lines stays well under 900 KB, so lower the limit + with patch('cronitor.ingest.MAX_EVENT_BYTES', 60000): + cronitor.capture_exception(e, extra={'batch': 42}) + self.assertTrue(cronitor.flush(2.0)) + item_header, event = self.send.items('event')[0] + self.assertLessEqual(item_header['length'], 60000) + values = event['exception']['values'] + self.assertEqual(len(values), 10) + for value in values: + frames = value['stacktrace']['frames'] + self.assertEqual(len(frames), 20) + self.assertEqual(frames[-1]['context_line'].strip(), "raise ValueError('bottom %d' % i)") + self.assertTrue(event['extra']['_trimmed'].startswith( + 'source context dropped; extra dropped; frames cut to the last 20 per exception')) + class CaptureMessageTests(CaptureTestCase): diff --git a/cronitor/tests/test_ingest.py b/cronitor/tests/test_ingest.py index 96e144c..95d980c 100644 --- a/cronitor/tests/test_ingest.py +++ b/cronitor/tests/test_ingest.py @@ -28,6 +28,16 @@ def _record(body, level='info'): return {'timestamp': 1761768000.5, 'level': level, 'body': body, 'attributes': {}} +def _exception_event(exceptions=10, frames=100, line='x' * 1000, extra=None): + """An event with a chain of exceptions, each with frames carrying source context.""" + def frame(n): + return {'filename': 'app.py', 'function': 'f%d' % n, 'lineno': n, 'context_line': line, + 'pre_context': ['p' * 100] * 5, 'post_context': ['q' * 100] * 5} + values = [{'type': 'ValueError', 'value': 'v%d' % i, 'stacktrace': {'frames': [frame(n) for n in range(frames)]}} + for i in range(exceptions)] + return _event(exception={'values': values}, extra=dict(extra or {})) + + class EnvelopeSerializationTests(unittest.TestCase): def test_serialize_envelope_layout(self): @@ -71,6 +81,63 @@ def test_format_timestamp(self): self.assertEqual(ingest.format_timestamp(stamp), '2026-10-29T20:00:00.123456Z') +class EventSizeTests(unittest.TestCase): + """The server drops event items over 1 MB, so oversized events are trimmed to 900 KB.""" + + def setUp(self): + self._saved_key = cronitor.api_key + cronitor.api_key = FAKE_API_KEY + self.send = RecordingSend() + self.transport = ingest.Transport(send=self.send) + + def tearDown(self): + cronitor.api_key = self._saved_key + + def sent_event(self, event): + self.assertTrue(self.transport.submit_event(event)) + self.assertTrue(self.transport.flush(5.0)) + item_header, payload = self.send.items('event')[0] + self.assertLessEqual(item_header['length'], ingest.MAX_EVENT_BYTES) + return payload + + def test_small_event_is_unchanged(self): + event = _exception_event(exceptions=1, frames=5, extra={'rows': 3}) + self.assertEqual(self.sent_event(event), event) + + def test_source_context_is_dropped_first(self): + event = _exception_event(line='x' * 200, extra={'rows': 3}) + self.assertGreater(len(ingest.json_bytes(event)), ingest.MAX_EVENT_BYTES) + sent = self.sent_event(event) + for value in sent['exception']['values']: + frames = value['stacktrace']['frames'] + self.assertEqual(len(frames), 100) + for frame in frames: + self.assertNotIn('pre_context', frame) + self.assertNotIn('post_context', frame) + self.assertEqual(frame['context_line'], 'x' * 200) + self.assertEqual(sent['extra'], {'rows': 3, '_trimmed': 'source context dropped: event over 900 KB'}) + + def test_huge_extra_is_dropped(self): + sent = self.sent_event(_event(message={'formatted': 'hi'}, extra={'blob': 'x' * 2000000, 'rows': 3})) + self.assertEqual(sent['extra'], {'_trimmed': 'extra dropped: event over 900 KB'}) + self.assertEqual(sent['message'], {'formatted': 'hi'}) + + def test_frames_are_cut_to_the_last_twenty_per_exception(self): + event = _exception_event(extra={'rows': 3}) + sent = self.sent_event(event) + values = sent['exception']['values'] + self.assertEqual(len(values), 10) + for value in values: + self.assertEqual([f['function'] for f in value['stacktrace']['frames']], + ['f%d' % n for n in range(80, 100)]) + self.assertEqual(sent['extra'], {'_trimmed': 'source context dropped; extra dropped; ' + 'frames cut to the last 20 per exception: event over 900 KB'}) + # the caller's event is left as it was + self.assertEqual(event['extra'], {'rows': 3}) + self.assertEqual(len(event['exception']['values'][0]['stacktrace']['frames']), 100) + self.assertIn('pre_context', event['exception']['values'][0]['stacktrace']['frames'][0]) + + class VersionTests(unittest.TestCase): def test_sdk_version_matches_setup_py(self): From a7ea2f8857374dd12f58590dfc225da91bd32c60 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 29 Oct 2026 22:19:24 +0000 Subject: [PATCH 15/18] Cap log attributes like the server and default LogHandler to INFO Attribute keys are cut to 64 characters and values to 400, except the exception stack trace and message and the message template, which keep 8,000 like the body; a record keeps at most 50 attributes. LogHandler now defaults to INFO, so a root logger at DEBUG no longer ships every library's debug lines; LogHandler(level=logging.DEBUG) opts in. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01B4Z4DjN96ccpNoVRZuoCxo --- README.md | 4 +++- cronitor/capture.py | 23 ++++++++++++------ cronitor/tests/test_capture.py | 43 ++++++++++++++++++++++++++++++++-- 3 files changed, 60 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 5b14924..a80f24a 100644 --- a/README.md +++ b/README.md @@ -173,9 +173,11 @@ The body is formatted with `str.format`, and the template and parameters are kep ```python import logging -logging.getLogger().addHandler(cronitor.LogHandler(level=logging.INFO)) +logging.getLogger().addHandler(cronitor.LogHandler()) ``` +The handler ships `INFO` and above by default, so a root logger set to `DEBUG` does not send every library's debug lines. Use `cronitor.LogHandler(level=logging.DEBUG)` to include them. A record keeps at most 50 attributes, with keys cut to 64 characters and values to 400 (8,000 for the body, the message template and the exception message and stack trace). + Logs are batched (100 records or 5 seconds). Queued events and logs are flushed when the process exits; call `cronitor.flush(timeout=2.0)` to flush earlier, for example at the end of a serverless handler. > In 5.0 `cronitor.logger` became this log shipper. Calls written for the stdlib logger it used to be keep working: %-style arguments (`cronitor.logger.info('Synced %s rows', 120)`), `warn`, `critical`, `exception` (an error log with the exception being handled: `exception.type`, `exception.message` and `exception.stacktrace`) and `log(level, ...)` with a stdlib level number or name. Configuration calls such as `setLevel` still reach `logging.getLogger('cronitor')`, which the package's own diagnostics use. diff --git a/cronitor/capture.py b/cronitor/capture.py index d1086f3..22fe1b5 100644 --- a/cronitor/capture.py +++ b/cronitor/capture.py @@ -34,7 +34,11 @@ MAX_TAG_KEY_LENGTH = 64 MAX_TAG_VALUE_LENGTH = 400 MAX_ATTRIBUTES = 50 -MAX_ATTRIBUTE_VALUE_LENGTH = 8000 +MAX_ATTRIBUTE_KEY_LENGTH = 64 +MAX_ATTRIBUTE_VALUE_LENGTH = 400 +# log attributes holding long text, which the server keeps as long as a body +TEXT_ATTRIBUTES = frozenset(['exception.stacktrace', 'exception.message', 'sentry.message.template']) +MAX_TEXT_ATTRIBUTE_LENGTH = 8000 MAX_CHAINED_EXCEPTIONS = 10 MAX_FRAMES = 100 MAX_LINE_LENGTH = 1000 @@ -420,7 +424,7 @@ def _exception_attributes(exc_type, exc_value, tb): 'exception.type': getattr(exc_type, '__name__', _safe_str(exc_type)), 'exception.message': _safe_str(exc_value), # keep the end, where the crash site and the message are - 'exception.stacktrace': stacktrace[-MAX_ATTRIBUTE_VALUE_LENGTH:], + 'exception.stacktrace': stacktrace[-MAX_TEXT_ATTRIBUTE_LENGTH:], } @@ -463,7 +467,7 @@ def _log_record(level, body, attributes, timestamp=None): if service: attrs[SERVICE_TAG] = _safe_str(service) for key, value in user.items(): - key = _safe_str(key) + key = _truncate(_safe_str(key), MAX_ATTRIBUTE_KEY_LENGTH) if key in attrs or len(attrs) >= MAX_ATTRIBUTES: continue attrs[key] = value @@ -472,11 +476,13 @@ def _log_record(level, body, attributes, timestamp=None): 'timestamp': time.time() if timestamp is None else float(timestamp), 'level': level, 'body': _truncate(body, MAX_LOG_BODY_LENGTH), - 'attributes': {key: _typed(value) for key, value in attrs.items()}, + 'attributes': {key: _typed(value, MAX_TEXT_ATTRIBUTE_LENGTH if key in TEXT_ATTRIBUTES + else MAX_ATTRIBUTE_VALUE_LENGTH) + for key, value in attrs.items()}, } -def _typed(value): +def _typed(value, max_length): if isinstance(value, bool): return {'value': value, 'type': 'boolean'} if isinstance(value, int): @@ -485,7 +491,7 @@ def _typed(value): return {'value': value, 'type': 'double'} if not isinstance(value, str): value = _safe_repr(value) - return {'value': _truncate(value, MAX_ATTRIBUTE_VALUE_LENGTH), 'type': 'string'} + return {'value': _truncate(value, max_length), 'type': 'string'} # logging integration @@ -514,9 +520,12 @@ class LogHandler(logging.Handler): Records are batched by the background transport. A record with exc_info carries the formatted traceback in the ``exception.stacktrace`` attribute; no separate exception event is sent. + + The default level is INFO, so a root logger at DEBUG does not ship every + library's debug lines; pass ``level=logging.DEBUG`` to include them. """ - def __init__(self, level=logging.NOTSET): + def __init__(self, level=logging.INFO): super(LogHandler, self).__init__(level) def emit(self, record): diff --git a/cronitor/tests/test_capture.py b/cronitor/tests/test_capture.py index a3f06e2..a0d98b8 100644 --- a/cronitor/tests/test_capture.py +++ b/cronitor/tests/test_capture.py @@ -455,6 +455,28 @@ def test_attributes_are_capped(self): self.assertEqual(len(record['attributes']), 50) self.assertIn('sentry.severity_number', record['attributes']) + def test_attribute_keys_and_values_are_capped(self): + cronitor.logger.info('caps', **{'k' * 100: 'v', 'k' * 64 + 'other': 'w', + 'plain': 'x' * 1000, 'items': list(range(1000))}) + attributes = self.flushed_logs()[0]['attributes'] + self.assertEqual(attributes['k' * 64], {'value': 'v', 'type': 'string'}) + self.assertTrue(all(len(key) <= 64 for key in attributes)) + self.assertEqual(len(attributes['plain']['value']), 400) + self.assertEqual(len(attributes['items']['value']), 400) + + def test_template_and_exception_text_keep_8000_characters(self): + template = '{n} ' + 't' * 9000 + try: + raise ValueError('m' * 9000) + except ValueError: + cronitor.logger.exception(template, n='p' * 1000) + record = self.flushed_logs()[0] + self.assertEqual(len(record['body']), 8000) + self.assertEqual(_attr(record, 'sentry.message.template')['value'], template[:8000]) + self.assertEqual(len(_attr(record, 'sentry.message.parameter.n')['value']), 400) + self.assertEqual(len(_attr(record, 'exception.message')['value']), 8000) + self.assertEqual(len(_attr(record, 'exception.stacktrace')['value']), 8000) + def test_stdlib_configuration_calls_still_work(self): import logging stdlib = logging.getLogger('cronitor') @@ -679,7 +701,7 @@ def setUp(self): self.log = logging.getLogger('cronitor.tests.handler') self.log.propagate = False self.log.setLevel(1) - self.handler = cronitor.LogHandler() + self.handler = cronitor.LogHandler(level=logging.NOTSET) self.log.addHandler(self.handler) self.addCleanup(self.log.removeHandler, self.handler) @@ -757,7 +779,24 @@ def test_handler_level(self): def test_handler_level_argument(self): self.assertEqual(cronitor.LogHandler(logging.ERROR).level, logging.ERROR) - self.assertEqual(cronitor.LogHandler().level, logging.NOTSET) + self.assertEqual(cronitor.LogHandler(level=logging.DEBUG).level, logging.DEBUG) + + def test_default_level_is_info(self): + # a root logger at DEBUG would otherwise ship every library's debug lines + self.log.removeHandler(self.handler) + handler = cronitor.LogHandler() + self.assertEqual(handler.level, logging.INFO) + self.log.addHandler(handler) + self.addCleanup(self.log.removeHandler, handler) + self.log.debug('dropped') + self.log.info('kept') + self.assertEqual([r['body'] for r in self.flushed_logs()], ['kept']) + + def test_long_parameters_are_capped(self): + self.log.info('%s', 'p' * 1000) + record = self.flushed_logs()[0] + self.assertEqual(len(record['body']), 1000) + self.assertEqual(len(_attr(record, 'sentry.message.parameter.0')['value']), 400) def test_records_inside_a_job_are_bound(self): @cronitor.job('handler-job') From 8626a35c0669e345beef7890f6c7408541d12e77 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 29 Oct 2026 22:21:18 +0000 Subject: [PATCH 16/18] Drop envelopes while rate limited instead of sleeping the sender After a 429 the sender thread slept until the limit lifted, so every item queued behind it waited too and was lost when the 2 second exit flush gave up. Envelopes sent during the limit window are now dropped, counted in Transport.dropped and logged once per window. X-Sentry-Rate-Limits is read before Retry-After, as Sentry's SDKs do. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01B4Z4DjN96ccpNoVRZuoCxo --- cronitor/ingest.py | 54 ++++++++++++++------- cronitor/tests/test_ingest.py | 89 ++++++++++++++++++++++++++--------- 2 files changed, 103 insertions(+), 40 deletions(-) diff --git a/cronitor/ingest.py b/cronitor/ingest.py index 1c9a220..bd57098 100644 --- a/cronitor/ingest.py +++ b/cronitor/ingest.py @@ -232,18 +232,27 @@ def in_worker_thread(): return getattr(_worker_state, 'active', False) +def _seconds(value): + try: + seconds = float(value) + except (TypeError, ValueError): + return None + return seconds if math.isfinite(seconds) else None + + def _retry_after(response): + """Seconds to stop sending after a 429, at most MAX_RETRY_AFTER. + + As in Sentry's SDKs, X-Sentry-Rate-Limits wins over Retry-After; the first + field of its first entry is the retry-after in seconds. With neither, the maximum. + """ headers = getattr(response, 'headers', None) or {} delay = None - try: - delay = float(headers.get('Retry-After')) - except (TypeError, ValueError): - limits = headers.get('X-Sentry-Rate-Limits') - if limits: - try: - delay = float(limits.split(',')[0].split(':')[0]) - except ValueError: - delay = None + limits = headers.get('X-Sentry-Rate-Limits') + if limits: + delay = _seconds(limits.split(',')[0].split(':')[0]) + if delay is None: + delay = _seconds(headers.get('Retry-After')) if delay is None: delay = MAX_RETRY_AFTER return max(0.0, min(delay, MAX_RETRY_AFTER)) @@ -254,12 +263,12 @@ class Transport(object): ``send(url, data, headers, timeout)`` performs the HTTP request and returns a response with ``status_code`` and ``headers``; it is injectable for tests. + ``dropped`` counts the items lost to a full queue or to a rate limit. """ - def __init__(self, send=None, sleep=None, maxsize=MAX_QUEUE_SIZE, + def __init__(self, send=None, maxsize=MAX_QUEUE_SIZE, batch_size=LOG_BATCH_SIZE, batch_interval=LOG_BATCH_INTERVAL): self._send = send or self._http_send - self._sleep = sleep or time.sleep self._maxsize = maxsize self._batch_size = batch_size self._batch_interval = batch_interval @@ -268,6 +277,7 @@ def __init__(self, send=None, sleep=None, maxsize=MAX_QUEUE_SIZE, self._thread = None self._pid = None self._rate_limited_until = 0.0 + self._reported_rate_limit = False self._reported_missing_key = False self.dropped = 0 @@ -369,7 +379,7 @@ def _run(self, q): deadline = time.monotonic() + self._batch_interval if len(batch) >= self._batch_size: del buffers[(url, api_key)] - self._deliver(url, api_key, log_envelope(batch)) + self._deliver(url, api_key, log_envelope(batch), len(batch)) if not buffers: deadline = None elif kind == 'flush': @@ -385,14 +395,21 @@ def _flush_logs(self, buffers): while buffers: (url, api_key), batch = buffers.popitem() try: - self._deliver(url, api_key, log_envelope(batch)) + self._deliver(url, api_key, log_envelope(batch), len(batch)) except Exception as e: logger.warning('Cronitor could not send logs: %s', e) - def _deliver(self, url, api_key, body): - wait = self._rate_limited_until - time.monotonic() - if wait > 0: - self._sleep(wait) + def _deliver(self, url, api_key, body, count=1): + """Send one envelope holding ``count`` items, or drop it while rate limited.""" + left = self._rate_limited_until - time.monotonic() + if left > 0: + # dropped rather than waited out, so the items queued behind it are not + # delayed into the exit flush and lost there + self.dropped += count + if not self._reported_rate_limit: + self._reported_rate_limit = True + logger.warning('Cronitor is rate limited for %.0f more seconds; dropping envelopes until then.', left) + return try: response = self._send(url, gzip.compress(body, 6), request_headers(api_key), SEND_TIMEOUT) except Exception as e: @@ -402,7 +419,8 @@ def _deliver(self, url, api_key, body): if status == 429: delay = _retry_after(response) self._rate_limited_until = time.monotonic() + delay - logger.warning('Cronitor rate limited the envelope; pausing sends for %.0f seconds.', delay) + self._reported_rate_limit = False + logger.warning('Cronitor rate limited the envelope (HTTP 429); not sending for %.0f seconds.', delay) elif status is not None and status >= 400: logger.warning('Cronitor rejected an envelope with HTTP %s.', status) diff --git a/cronitor/tests/test_ingest.py b/cronitor/tests/test_ingest.py index 95d980c..94b2598 100644 --- a/cronitor/tests/test_ingest.py +++ b/cronitor/tests/test_ingest.py @@ -197,9 +197,8 @@ def setUp(self): self._saved_url = cronitor.ingest_url cronitor.api_key = FAKE_API_KEY cronitor.ingest_url = ingest.DEFAULT_INGEST_URL - self.sleeps = [] self.send = RecordingSend() - self.transport = ingest.Transport(send=self.send, sleep=self.sleeps.append) + self.transport = ingest.Transport(send=self.send) def tearDown(self): self.transport.flush(1.0) @@ -316,37 +315,80 @@ def test_error_status_is_logged(self): self.transport.flush(2.0) self.assertIn('403', '\n'.join(logs.output)) - def test_429_sleeps_retry_after_before_next_send(self): + def rate_limit_left(self): + return self.transport._rate_limited_until - time.monotonic() + + def test_429_drops_envelopes_until_retry_after_without_waiting(self): self.send.responses = [FakeResponse(429, {'Retry-After': '7'})] + with self.assertLogs('cronitor.ingest', 'WARNING') as logs: + self.transport.submit_event(_event('1' * 32)) + self.assertTrue(self.transport.flush(2.0)) + self.assertAlmostEqual(self.rate_limit_left(), 7, delta=1) + self.transport.submit_event(_event('2' * 32)) + for i in range(3): + self.transport.submit_log(_record('during the limit %d' % i)) + # nothing waits out the limit, so queued items are not held past the exit flush + self.assertTrue(self.transport.flush(2.0)) + self.assertEqual(len(self.send.calls), 1) + self.assertEqual(self.transport.dropped, 4) + # the 429 and the first drop in its window are logged, later drops are not + self.assertEqual(len(logs.output), 2, logs.output) + self.assertIn('rate limited', logs.output[1]) + + self.transport._rate_limited_until = time.monotonic() - 1 # the window has passed + self.transport.submit_event(_event('3' * 32)) + self.assertTrue(self.transport.flush(2.0)) + self.assertEqual([h['event_id'] for h, _ in self.send.envelopes()], ['1' * 32, '3' * 32]) + + def test_drops_are_logged_once_per_limit_window(self): + self.send.responses = [FakeResponse(429, {'Retry-After': '5'}), FakeResponse(429, {'Retry-After': '5'})] + with self.assertLogs('cronitor.ingest', 'WARNING') as logs: + for _ in range(2): + self.transport.submit_event(_event('1' * 32)) + self.transport.flush(2.0) + self.transport.submit_event(_event('2' * 32)) + self.transport.submit_event(_event('3' * 32)) + self.transport.flush(2.0) + self.transport._rate_limited_until = time.monotonic() - 1 + self.assertEqual(len(self.send.calls), 2) + self.assertEqual(self.transport.dropped, 4) + self.assertEqual(len(logs.output), 4, logs.output) + + def test_sentry_rate_limits_header_wins_over_retry_after(self): + self.send.responses = [FakeResponse(429, {'Retry-After': '30', + 'X-Sentry-Rate-Limits': '5:error;default:organization, 50:transaction'})] with self.assertLogs('cronitor.ingest', 'WARNING'): self.transport.submit_event(_event('1' * 32)) self.transport.flush(2.0) - self.assertEqual(self.sleeps, []) - self.transport.submit_event(_event('2' * 32)) - self.transport.flush(2.0) - self.assertEqual(len(self.sleeps), 1) - self.assertAlmostEqual(self.sleeps[0], 7, delta=1) - self.assertEqual(len(self.send.calls), 2) + self.assertAlmostEqual(self.rate_limit_left(), 5, delta=1) + + def test_retry_after_parsing(self): + def retry_after(headers): + return ingest._retry_after(FakeResponse(429, headers)) + + self.assertEqual(retry_after({'X-Sentry-Rate-Limits': '12::organization', 'Retry-After': '30'}), 12) + self.assertEqual(retry_after({'X-Sentry-Rate-Limits': 'garbage', 'Retry-After': '30'}), 30) + self.assertEqual(retry_after({'X-Sentry-Rate-Limits': '3600:error'}), 60) + self.assertEqual(retry_after({'Retry-After': '7'}), 7) + self.assertEqual(retry_after({'Retry-After': '3600'}), 60) + self.assertEqual(retry_after({'Retry-After': 'Wed, 21 Oct 2026 07:28:00 GMT'}), 60) + self.assertEqual(retry_after({'Retry-After': 'nan'}), 60) + self.assertEqual(retry_after({}), 60) def test_429_retry_after_is_capped_at_60_seconds(self): self.send.responses = [FakeResponse(429, {'Retry-After': '3600'})] with self.assertLogs('cronitor.ingest', 'WARNING'): self.transport.submit_event(_event('1' * 32)) self.transport.flush(2.0) - self.transport.submit_log(_record('after the limit')) - self.transport.flush(2.0) - self.assertEqual(len(self.sleeps), 1) - self.assertLessEqual(self.sleeps[0], 60) - self.assertGreater(self.sleeps[0], 58) + self.assertLessEqual(self.rate_limit_left(), 60) + self.assertGreater(self.rate_limit_left(), 58) def test_429_without_retry_after_waits_60_seconds(self): self.send.responses = [FakeResponse(429)] with self.assertLogs('cronitor.ingest', 'WARNING'): self.transport.submit_event(_event('1' * 32)) self.transport.flush(2.0) - self.transport.submit_event(_event('2' * 32)) - self.transport.flush(2.0) - self.assertGreater(self.sleeps[0], 58) + self.assertGreater(self.rate_limit_left(), 58) def test_full_queue_drops_and_counts(self): release = threading.Event() @@ -477,13 +519,18 @@ def tearDown(self): cronitor.api_key, cronitor.ingest_url = self._saved def test_envelopes_and_pings_reach_the_ingest_url(self): - sleeps = [] - transport = ingest.Transport(sleep=sleeps.append) - self.statuses.extend([(200, {}), (429, {'Retry-After': '3'}), (200, {})]) + transport = ingest.Transport() + self.statuses.extend([(200, {}), (429, {'Retry-After': '30', 'X-Sentry-Rate-Limits': '3:error:organization'}), + (200, {})]) transport.submit_event(_event('1' * 32)) transport.submit_event(_event('2' * 32)) with self.assertLogs('cronitor.ingest', 'WARNING'): self.assertTrue(transport.flush(5.0)) + self.assertAlmostEqual(transport._rate_limited_until - time.monotonic(), 3, delta=1) + transport.submit_log(_record('during the limit')) + self.assertTrue(transport.flush(5.0)) + self.assertEqual(transport.dropped, 1) + transport._rate_limited_until = time.monotonic() - 1 transport.submit_log(_record('after 429')) self.assertTrue(transport.flush(5.0)) @@ -496,8 +543,6 @@ def test_envelopes_and_pings_reach_the_ingest_url(self): self.assertTrue(headers['X-Sentry-Auth'].startswith('Sentry sentry_key=%s, sentry_version=7,' % FAKE_API_KEY)) header, items = parse_envelope(body) self.assertEqual(header['event_id'], '1' * 32) - self.assertEqual(len(sleeps), 1) - self.assertAlmostEqual(sleeps[0], 3, delta=1) self.assertEqual(parse_envelope(self.received[2][3])[1][0][1]['items'][0]['body'], 'after 429') cronitor.Monitor('local-job').ping(state='run') From 3f886a8a4ebb1a84a31e43861757ce066c041e9a Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 29 Oct 2026 22:21:31 +0000 Subject: [PATCH 17/18] Note in the README that threads do not inherit the job binding Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01B4Z4DjN96ccpNoVRZuoCxo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a80f24a..9287c77 100644 --- a/README.md +++ b/README.md @@ -142,7 +142,7 @@ cronitor.service = 'billing-api' # optional, or CRONITOR_SERVICE: the servi When a function decorated with `@cronitor.job` raises, the `fail` ping is sent as before and an exception event with the full stack trace follows, bound to the same monitor and run. Set `cronitor.capture_exceptions = False` to send only the ping. -Anything captured while the job runs (exceptions, messages, logs) is bound to the monitor and the run automatically. +Anything captured while the job runs (exceptions, messages, logs) is bound to the monitor and the run automatically. Threads started inside a `@cronitor.job` function do not inherit this binding (it is held in a `ContextVar`), so pass `monitor=` and `series=` explicitly to captures made there; `cronitor.capture.current_job()`, called in the job function, returns both. #### Capturing exceptions and messages From 3a96477373307063cbcc1257ebb5b384bc7452ad Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 29 Oct 2026 22:22:52 +0000 Subject: [PATCH 18/18] Ignore non-integer status codes from transport stubs Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01B4Z4DjN96ccpNoVRZuoCxo --- cronitor/ingest.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/cronitor/ingest.py b/cronitor/ingest.py index bd57098..115f6ee 100644 --- a/cronitor/ingest.py +++ b/cronitor/ingest.py @@ -416,6 +416,9 @@ def _deliver(self, url, api_key, body, count=1): logger.warning('Cronitor could not send an envelope to %s: %s', url, e) return status = getattr(response, 'status_code', None) + if not isinstance(status, int): + # a transport stub or an unexpected response object: nothing to act on + return if status == 429: delay = _retry_after(response) self._rate_limited_until = time.monotonic() + delay