diff --git a/README.md b/README.md index a89b506..9287c77 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,76 @@ 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 +cronitor.service = 'billing-api' # optional, or CRONITOR_SERVICE: the service monitor these events belong to +``` + +#### 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. 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 + +```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()) +``` + +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. + +#### 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/{service_monitor_id}') +sentry_sdk.set_tag('cronitor.monitor', 'nightly-job') +``` + +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 ### YAML Configuration File @@ -299,6 +370,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. `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 e48dceb..75e1bf0 100644 --- a/cronitor/__init__.py +++ b/cronitor/__init__.py @@ -10,9 +10,13 @@ import threading from .monitor import Monitor, YAML +from . import capture, ingest +from .ingest import flush +from .capture import capture_exception, capture_message, logger, LogHandler -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) @@ -23,6 +27,15 @@ 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 +# attached to exception events and logs +release = os.getenv('CRONITOR_RELEASE', 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 + celerybeat_only = False # monitor attributes can be synced at process startup @@ -54,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): @@ -68,17 +90,25 @@ def wrapped(*args, **kwargs): monitor = Monitor(key, env=env) # use start as the series param to match run/fail/complete correctly - monitor.ping(state=State.RUN, series=start) + _safe_ping(monitor, state=State.RUN, series=start) + # 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) + _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) raise e + finally: + capture.unbind_job(token) duration = datetime.now().timestamp() - start message = str(out) if all([log_output, include_output]) else None - monitor.ping(state=State.COMPLETE, message=message, metrics={'duration': duration}, series=start) + _safe_ping(monitor, state=State.COMPLETE, message=message, metrics={'duration': duration}, series=start) return out return wrapped @@ -103,10 +133,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/_version.py b/cronitor/_version.py new file mode 100644 index 0000000..a0f6658 --- /dev/null +++ b/cronitor/_version.py @@ -0,0 +1 @@ +__version__ = '5.0.0' diff --git a/cronitor/capture.py b/cronitor/capture.py new file mode 100644 index 0000000..22fe1b5 --- /dev/null +++ b/cronitor/capture.py @@ -0,0 +1,580 @@ +"""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 math +import os +import socket +import sys +import sysconfig +import time +import traceback +import uuid +from collections import namedtuple +from collections.abc import Mapping + +import cronitor +from . import ingest + +_log = logging.getLogger(__name__) + +MONITOR_TAG = 'cronitor.monitor' +SERIES_TAG = 'cronitor.series' +SERVICE_TAG = 'cronitor.service' + +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_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 +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. + + 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, *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 warning(self, body, *args, **attributes): + _capture_log('warn', body, attributes, args=args) + + def error(self, body, *args, **attributes): + _capture_log('error', body, attributes, args=args) + + def fatal(self, body, *args, **attributes): + _capture_log('fatal', body, attributes, args=args) + + warn = warning + critical = fatal + + 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()) + + 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']) + + 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 + 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) + 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, MAX_TEXT_ATTRIBUTE_LENGTH if key in TEXT_ATTRIBUTES + else MAX_ATTRIBUTE_VALUE_LENGTH) + for key, value in attrs.items()}, + } + + +def _typed(value, max_length): + if isinstance(value, bool): + return {'value': value, 'type': 'boolean'} + if isinstance(value, int): + return {'value': value, 'type': 'integer'} + if isinstance(value, float) and math.isfinite(value): + return {'value': value, 'type': 'double'} + if not isinstance(value, str): + value = _safe_repr(value) + return {'value': _truncate(value, max_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. + + 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.INFO): + 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: + 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: + self.handleError(record) + + +# 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/ingest.py b/cronitor/ingest.py new file mode 100644 index 0000000..115f6ee --- /dev/null +++ b/cronitor/ingest.py @@ -0,0 +1,477 @@ +"""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 math +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 +# 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' + +_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_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): + """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): + """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_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} + 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 _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 + 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)) + + +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. + ``dropped`` counts the items lost to a full queue or to a rate limit. + """ + + 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._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._reported_rate_limit = False + self._reported_missing_key = False + 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'], event_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 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 + + 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) + 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() + 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), len(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), len(batch)) + except Exception as e: + logger.warning('Cronitor could not send logs: %s', e) + + 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: + 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 + 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) + + 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..6813176 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 @@ -168,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.') @@ -207,7 +220,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..3406888 --- /dev/null +++ b/cronitor/tests/envelope_parser.py @@ -0,0 +1,108 @@ +"""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 _reject_constant(name): + raise ValueError('not valid JSON: %s' % name) + + +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'), parse_constant=_reject_constant))) + 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_capture.py b/cronitor/tests/test_capture.py new file mode 100644 index 0000000..a0d98b8 --- /dev/null +++ b/cronitor/tests/test_capture.py @@ -0,0 +1,864 @@ +import json +import logging +import os +import re +import socket +import sys +import time +import unittest + +import requests +from unittest.mock import patch + +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(), []) + + 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): + + 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('