Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 73 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand Down
44 changes: 37 additions & 7 deletions cronitor/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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
Expand Down Expand Up @@ -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):

Expand All @@ -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
Expand All @@ -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):
Expand Down
1 change: 1 addition & 0 deletions cronitor/_version.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
__version__ = '5.0.0'
Loading
Loading