Tern

sentry

The sentry package reports errors and messages to Sentry, the hosted service or a self-hosted install. Runtime errors come with native stack traces, and errors inside web handlers come with the request and route they happened in. It's a package of its own (import sentry), so programs that don't report errors don't carry it.

Compiles (not run here)
import os
import sentry
import tls
import roost

fn main():
    o = sentry.options()
    o.release = "shop@1.4.2"
    c = sentry.init(os.env("SENTRY_DSN", ""), o)   # no DSN: capturing does nothing
    sentry.install(c)                             # every runtime error becomes an event
    r = roost.router()
    r.get("/orders/{id}", fn(req) roost.text("order " + req.param("id")))
    r.layer(sentry.middleware(c))                 # events from a request carry it
    c.capture_message("shop starting", "info")
    roost.serve(r, 8080)                            # SIGINT/SIGTERM: drain, then return
    c.close()                                     # send what's still queued

A DSN that starts with https:// needs import tls, as for any HTTPS request. Without a DSN, or with a bad one, c.ok() is false and c.error() says why. Capturing then does nothing, so the same program runs in development without Sentry.

Setting up

fn options() Options
fn init(dsn: str, o: Options) Client
fn ok(c: Client) bool
fn error(c: Client) str

sentry.options() fills in the defaults; change the fields you need before calling init:

fielddefault
release$SENTRY_RELEASEthe version, e.g. "shop@1.4.2" (Sentry tracks regressions by release)
environment$SENTRY_ENVIRONMENT, else "production"
server_name$HOSTNAME
sample_rate1.0the share of events sent
max_queue100events waiting to be sent; more are dropped
breadcrumbs50recent log records sent with each event
timeout_ms10000per request to Sentry
scrubsee Scrubbingnames whose values are hidden

Capturing

fn capture_message(c: Client, message: str, level: str) str
fn capture_error(c: Client, r: os.ErrorReport) str
fn capture_result[T](c: Client, r: Result[T, str]) str
fn install(c: Client)

Each returns the event's id (32 hex digits), or "" if nothing was queued: sending is off, the event wasn't sampled, the queue is full, or Sentry asked us to wait. Levels are "fatal", "error", "warning" (or "warn"), "info", and "debug".

capture_result sends an Err as an error event whose message is the error text, and ignores an Ok. It fits the library's error format ("pg: query failed: timeout"):

users: Result[[User], str] = db.fetch("SELECT id, name FROM users", [])
c.capture_result(users)

sentry.install(c) hands every runtime error to c through os.on_error. That includes a failed task, a web handler that answered 500, and the error that ends the program. Each one is sent before the hook returns, so the last error of a program that's crashing is reported too. The event holds the error's message, its stack (innermost frame with its file and line), and the executable's identity for symbolication (see Stack traces).

Scope: tags, user, request

fn set_tag(key: str, value: str)
fn set_extra(key: str, value: str)
fn set_user(id: str, email: str)
fn clear_scope()
fn middleware(c: Client) fn(roost.Request, fn(roost.Request) roost.Response) roost.Response

Tags, extra values, and the user apply to the events of the task that set them, including a runtime error in that task, and to tasks it spawns. They're kept in task-locals, so concurrent requests don't see each other's.

sentry.middleware(c) records the request for each event from inside a handler: method, URL, query string, headers, and the client's IP. It also sets the transaction to the matched route (GET /orders/{id}), so Sentry groups events by route rather than by URL. A panic inside the handler arrives with that request data too, since error reports carry the failing task's locals. Put it on the router after the routes (r.layer), like any middleware.

Scrubbing

The values of headers, query parameters, set_extra keys, and log fields are replaced with "[Filtered]" when the name, lowercased, contains one of o.scrub. By default those are auth, cookie, password, passwd, secret, token, key, session, and credential. That covers Authorization, Cookie, Set-Cookie, X-Api-Key, ?token=, api_key=, and the like. Add your own before init:

o = sentry.options()
o.scrub.push("ssn")
o.scrub.push("card")

Each event carries the last o.breadcrumbs records from log's memory (log.recent), with their fields scrubbed. By default the log keeps records at warn and up; log.keep("info") keeps info records too.

Sending

fn flush(c: Client, timeout_ms: int) bool
fn close(c: Client)
fn sent(c: Client) int
fn dropped(c: Client) int

Capturing builds the event, puts it on a queue, and returns; one background task per client sends the queue, so a slow or unreachable Sentry never holds up a request. The sender works like Sentry's own SDKs:

  • It retries after a network error or a 5xx answer, 1 s, 2 s, and 4 s later, then drops the event.
  • A 429 answer, or an X-Sentry-Rate-Limits header covering error events, makes the client drop new events until the time Sentry gave has passed.
  • The X-Sentry-Auth header and the envelope format are Sentry's current ones (protocol version 7).

flush waits, parking only the calling task, until the queue is empty and nothing is being sent, and returns false if timeout_ms passes first. close flushes for up to two seconds and stops the sender. Call it before main returns, since the program ends when main does.

Stack traces

Frames are sent as native addresses, with the function names Tern already knows (Tern names like load or roost._limited, and C symbols for the runtime). Each event also describes the executable: its build id (Mach-O UUID or ELF GNU build id), load address, and path. Sentry uses these to symbolicate the addresses, giving file names and lines for every frame, from a debug file you upload:

tern build app.tn -o app                        # keep this unstripped file
sentry-cli debug-files upload --org ORG --project PROJECT app
strip -o app.deploy app                         # deploy the stripped one if you like

For source lines in every frame, build with tern build -g (no optimization), or upload the file that dsymutil app makes on macOS. Frames from your own code are marked in-app; frames from the runtime, the standard library, and packages like roost and pg aren't.

Source: docs/packages/sentry.md. Every example on this page is compiled and run by tern x test docs.