NAME

Sentry::SDK - sentry.io integration

SYNOPSIS

use Sentry::SDK;

Sentry::SDK->init({
  dsn => "https://examplePublicKey@o0.ingest.sentry.io/0",

  # Adjust this value in production
  traces_sample_rate => 1.0,
});

DESCRIPTION

Captures errors and messages and records performance data (transactions) and sends them to Sentry, following the behavior of Sentry's official SDKs.

This is the reference of the API and the options. Sentry::SDK::Manual shows how to set the SDK up for each kind of application (scripts, CGI, FastCGI, mod_perl, PSGI, Mojolicious) and how to use it. Upgrading from 1.x: see the migration guide, MIGRATION.md.

SCOPES

Data attached to events (tags, the user, contexts, extra data, breadcrumbs, feature flags, the active span) lives in scopes. Like the other Sentry SDKs (see Sentry's scope model), this SDK has three of them in effect at any time:

global scope

One per process. Data that applies to every event; the client lives here.

isolation scope

One per unit of work: a request (the framework plugins clone one for every request) or a job ("with_isolation_scope"). "set_tag, set_tags", "set_user", "add_breadcrumb", "add_feature_flag", "configure_scope" etc. write here. It also holds the id of the last event ("last_event_id") and the trace that errors outside of transactions are linked by.

current scope

One per block of code ("with_scope"). It holds the active span.

An event gets the data of all three, in the order global, isolation, current: data of a later scope wins, and data given to the capture call wins over all of them. Breadcrumbs of all three are combined in the order they were added; feature flags of a later scope count as evaluated after those of an earlier one.

Switching scopes uses Perl's local: a block ("with_scope", "with_isolation_scope") restores the previous scopes however it is left, also by an exception.

Callbacks of non-blocking code run after the block that registered them has been left. Callbacks of Mojo::Promise, Mojo::IOLoop timers and non-blocking Mojo::UserAgent requests take the scopes along (see Sentry::Integration::MojoIOLoop), as do those of AnyEvent (see Sentry::Integration::AnyEvent) and AnyEvent::HTTP requests; for others use "bind_scopes" in Sentry::Scope.

DISTRIBUTED TRACING

A service called by another one continues its trace, so that Sentry shows one trace across both: the caller's http.client span is the parent of the callee's transaction, and the callee follows the caller's sampling decision. This works without configuration between services using this SDK or another Sentry SDK (see trace propagation):

outgoing requests

HTTP::Tiny, LWP::UserAgent, Mojo::UserAgent and AnyEvent::HTTP requests carry the sentry-trace and baggage headers (see "trace_propagation_targets"). Entries of other vendors in a baggage header the application sets are kept.

incoming requests

The framework and server integrations (Mojolicious, Plack, CGI::Application, mod_perl, FastCGI) continue the trace of the sentry-trace and baggage headers of a request. Malformed headers are ignored: the request starts a trace of its own.

processes

A process started with the environment variables SENTRY_TRACE and SENTRY_BAGGAGE (the values of the headers) continues their trace from "init" on, e.g. a job run by a traced service. Commands run with backticks, IPC::Open2, IPC::Open3 or IPC::Cmd get them from Sentry::Integration::Subprocess.

other units of work

Messages of a job queue and the like continue a trace with "continue_trace"; "get_traceparent, get_baggage" give the values to pass on, e.g. in HTML meta tags for a browser SDK.

The incoming sampling decision applies even if "traces_sample_rate" is 0; without one, the service decides with its own rate. All services of a trace decide with the same random number, so services with the same rate keep or drop a trace together. With tracing disabled (no "traces_sample_rate"), a service still passes the trace on, and its errors are linked to it.

The dynamic sampling context (release, environment, transaction name, sample rate etc. of the service that started the trace) is passed on in the baggage header unchanged and sent with every event of the trace, so that Sentry samples whole traces. Transaction names made from URLs (source url) are left out of it, as they may contain ids.

Traces of other Sentry organizations are not continued (see "org_id").

SENDING

Where an application serves many requests in one process, a sender process sends its events, like the background thread of sentry-python: the SDK hands each envelope to it through a socket and returns at once, so neither the response nor the worker waits for Sentry. That is the case under Plack::Middleware::SentrySDK (unless the server runs the application once, as Plack::Handler::CGI does), also with the Mojolicious plugin or CGI::Application served by a PSGI server, and with a FastCGI loop (Sentry::Integration::FCGI); each of them tells the SDK when it starts serving a request. Under mod_perl (Sentry::Integration::ModPerl) events are sent in the cleanup phase after the response instead, unless "background_sender" is 1: a sender per worker costs memory (see below), and an Apache runs many workers. The daemons of Mojolicious send in the background of their event loop anyway.

Each process gets its own sender on its first event, also each worker a preforking server forks; a worker never uses the sender of its parent. The sender is a new perl process (started with the perl and @INC of the worker) rather than a copy of the worker: it loads only the transport, HTTP::Tiny and IO::Socket::SSL, not the worker's memory. That costs about 20 to 30 MB resident per worker, much of it shared libraries, whose pages all senders share. One sender shared by all workers of a server would cost less, but is not implemented. It closes the files of the worker, ignores the signals a server sends its process group, and ends once its worker has ended and it has sent what it got, within "shutdown_timeout"; a child the worker forked without exec keeps it until that child ends or sends an event itself. It is started detached, so it is no child of the worker: the application's wait never sees it, and it leaves no zombie, also with $SIG{CHLD} ignored. Under taint mode it runs with PATH set to /usr/bin:/bin. ps shows it as sentry sender of the worker's pid.

The sender sends one envelope after the other, keeping the connection to Sentry open, and applies the rate limits and client reports itself. At most "transport_queue_size" envelopes wait for it; further ones are dropped (queue_overflow). If it ends unexpectedly, the envelopes it got are lost (network_error), those it did not get yet are sent by the worker itself, as are the following ones until another sender starts with the next event, at most every 30 seconds. When Sentry is slow (e.g. at exit), events are sent before transactions. If it cannot start at all (e.g. no fork, or the new perl cannot load the SDK), the process sends without it, as described next. "background_sender" turns it off.

As it ignores TERM, a service manager that signals the whole process group or cgroup (systemd's default KillMode=control-group) cannot stop it early: it ends on its own once its worker is gone, at most "shutdown_timeout" seconds later. With a slow or unreachable Sentry, a restart of the service may take that much longer.

Everywhere else, i.e. in scripts, under CGI and on Windows, starting a process would cost more than it saves: events are sent with HTTP::Tiny, and the application waits for the response, at most "http_timeout" seconds. Inside a running Mojo::IOLoop of an application using Mojolicious (its daemons, also preforking ones), they are sent in the background of the loop with Mojo::UserAgent instead, at most 30 at a time; further ones are dropped.

Without sender process, events of a request (of a CGI script, or served by CGI::Application::Plugin::Sentry or Plack::Middleware::SentrySDK) are held back and sent when the response is complete, at most "transport_queue_size" of them. No request is started after "http_timeout" seconds, so a request started just before may take up to twice that; the rest follows with the next request. If the request dies, they are sent before the exception leaves the SDK, so that a persistent process does not keep them until its next request; the error page waits for that at most "http_timeout" seconds in all. Pending events are sent at a normal exit of the process (also of a prefork worker stopped gracefully), within "shutdown_timeout"; with a sender process, the exit waits until it has sent them. Exits that skip END blocks (POSIX::_exit, exec, kill -9) lose what was not handed over yet. A forked child never sends events of its parent.

Failed requests are not retried. While Sentry rate-limits the project (X-Sentry-Rate-Limits, or Retry-After on status 429), events of the limited categories are dropped. After repeated network errors of requests the application waited for, events are dropped for a while (2 seconds, doubling up to 5 minutes). Requests in the background, and those cut short by the timeout of "flush", never suspend sending. A forked child keeps the suspensions of its parent. Whatever is dropped is counted and reported to Sentry (see "send_client_reports").

While Sentry rate-limits, sending is suspended or envelopes pile up, the SDK also samples fewer transactions, so that it adds less to the load on its own (see "enable_backpressure_handling").

For tests of an application, Sentry::Test captures what it sends instead:

use Sentry::Test;

my $sentry = Sentry::Test->start;

# ... exercise the application, e.g. with Test::Mojo ...

is $sentry->last_event->{message}, 'something went wrong';
is_deeply $sentry->discarded_events, [];
$sentry->clear;

INTEGRATIONS

Integrations instrument other modules. The default ones are enabled by "init" and become active once the application loads the module they instrument, before or after init; they never load it themselves. An integration that does not fit the installed version of its module warns once and switches itself off. See "integrations", "disabled_integrations" and "default_integrations" to configure them.

Web frameworks and servers:

Mojolicious::Plugin::SentrySDK

Plugin for Mojolicious applications.

CGI::Application::Plugin::Sentry, Sentry::Integration::CGIApplication

Every CGI::Application (default; the plugin adds initialization from the application's parameters).

Plack::Middleware::SentrySDK

Middleware for PSGI applications.

Sentry::Integration::FCGI

FastCGI loops of FCGI and CGI::Fast (default).

Sentry::Integration::CGI

The request of a CGI script (default).

Sentry::Integration::ModPerl

Every request of a mod_perl 2 server (default).

Sentry::Integration::NetServer

The parent of a preforking Net::Server, e.g. Starman's master (default): sends its logs and metrics while it runs.

Databases, caches, HTTP clients and templates (all default):

Sentry::Integration::DBI

Statements, transactions and connections of DBI.

Sentry::Integration::DBIxClass

The result sources of DBIx::Class statements, on the spans of the DBI integration, and its transactions (txn_do) and savepoints.

Sentry::Integration::MongoDB

Commands of the official MongoDB driver.

Sentry::Integration::Elasticsearch

Requests of Search::Elasticsearch.

Sentry::Integration::NetLDAP

Operations of Net::LDAP.

Sentry::Integration::Redis

Commands of Redis and Redis::Fast.

Sentry::Integration::CacheMemcached

Operations of Cache::Memcached.

Sentry::Integration::LwpUserAgent

Requests of LWP::UserAgent (and LWP::Simple, WWW::Mechanize).

Sentry::Integration::MojoUserAgent

Requests of Mojo::UserAgent.

Sentry::Integration::AnyEventHTTP

Requests of AnyEvent::HTTP.

Sentry::Integration::GraphQLClient

Requests of GraphQL::Client: the operation on the span of its HTTP request, a request that failed on the events of the unit of work.

Sentry::Integration::NetApnsSimple

Push notifications sent with Net::APNS::Simple.

Sentry::Integration::MojoTemplate

Rendering of Mojo::Template.

Sentry::Integration::TemplateToolkit

Rendering of Template (Template Toolkit).

Sentry::Integration::HttpTiny

Requests of HTTP::Tiny, other than the SDK's own.

Sentry::Integration::SoapLite

Calls of SOAP::Lite.

Sentry::Integration::NetFTP

Commands of Net::FTP.

Sentry::Integration::NetSMTP

Commands of Net::SMTP.

Sentry::Integration::MIMELite

Messages sent with MIME::Lite.

Sentry::Integration::HTMLTemplate

Parsing and rendering of HTML::Template.

Sentry::Integration::HTMLTemplatePro

Rendering of HTML::Template::Pro.

Sentry::Integration::LibXSLT

Stylesheets of XML::LibXSLT.

Sentry::Integration::ImageMagick

Reading, writing and processing images with Image::Magick and Graphics::Magick.

Sentry::Integration::NetAmazonS3

Operations of Net::Amazon::S3 and Net::Amazon::S3::Client.

Sentry::Integration::ArchiveZip

Reading, writing and extracting archives with Archive::Zip.

Logging (default, see Sentry::Integration::Logging):

Sentry::Integration::MojoLog

Messages of Mojo::Log.

Sentry::Integration::Log4perl

Messages of Log::Log4perl.

Runtime (default):

Sentry::Integration::DieHandler

Stack traces of string exceptions, and exceptions that end the program.

Sentry::Integration::MojoIOLoop

Scopes of callbacks of Mojo::IOLoop, Mojo::Promise and non-blocking Mojo::UserAgent requests, and their errors.

Sentry::Integration::AnyEvent

Scopes of callbacks of AnyEvent watchers, condition variables, AnyEvent::Handle and AnyEvent::DNS, with any backend.

Sentry::Integration::FunctionsToTrace

Spans for the functions of "functions_to_trace" (enabled by that option).

Sentry::Integration::Subprocess

Commands run with backticks, qx//, IPC::Open2, IPC::Open3 and IPC::Cmd (not system and exec).

Own integrations are written with Sentry::Integration::Base.

RELEASE HEALTH

With a "release", the SDK sends sessions, from which Sentry shows the health of a release: how many runs or requests had errors or crashed. This needs no configuration ("auto_session_tracking").

web applications

Each request is a session (request mode), as in sentry-python: an error event captured during the request makes it errored, an exception the request died with (which the integrations capture as unhandled) crashed. Sessions are counted per minute, release and environment and sent as one sessions item through the transport (the sender process where there is one): at the end of a request a minute or more after the first pending one, with every "flush", and at exit. Without a thread, a worker that waits for requests keeps them until its next request or its exit; one waiting in an AnyEvent loop (Twiggy) sends them once due (see Sentry::Integration::AnyEvent). A process ended by a signal it does not handle never reaches its exit and loses what it kept: Twiggy has no handler for TERM, the signal of systemd and docker stop, so give it one:

# app.psgi; our: a "my" variable is gone once the file is loaded
our $stop = AE::signal TERM => sub { exit };

This works with every web integration: Plack (any PSGI server, preforking ones too), Mojolicious (its daemons, also prefork and hypnotoad), mod_perl, FastCGI and CGI::Application under CGI.

other programs

Scripts, cron jobs, workers: the run of the program is one session (application mode, which sentry-python does not start on its own, but other SDKs do for applications), started by "init" and ended at exit, as exited or, after an uncaught exception, as crashed; it counts the errors captured meanwhile. It is sent at exit (or by "close") as a session item. A child forked without exec does not end the session of its parent. A program that turns out to serve web requests sends no session of its own, only those of the requests: also the parent process of preforking servers, which serves none itself. Applications with Mojolicious::Plugin::SentrySDK count as web applications from the start: their commands (hypnotoad hot deploys and stops, routes, eval, job queue workers) send no session.

Error events count when they carry an exception (at any level, as in sentry-python), or were captured with "capture_event" at level error or fatal; messages and log records never do. Events dropped by "ignore_errors", event processors or "before_send" do not count, those dropped by rate limits do, and so do those dropped by "sample_rate": the SDK samples before running event processors and "before_send", so an error those would drop counts if sampling drops it first. A program that is killed (kill -9, POSIX::_exit) sends no session, nor does a request the integration never sees the end of.

Sessions are rate limited and counted in client reports as data category session.

CRON MONITORING

Cron monitors tell when a job did not run, failed, or ran too long. A job checks in when it starts (in_progress) and when it ends (ok or error, with its duration), see check-ins:

# e.g. a script run by cron
Sentry::SDK->monitor(
  'nightly-report',
  sub { build_report() },
  {
    schedule       => { type => 'crontab', value => '0 2 * * *' },
    checkin_margin => 10,           # minutes
    max_runtime    => 60,           # minutes
    timezone       => 'Europe/Berlin',
  }
);

The monitor configuration is optional; with it, Sentry creates the monitor of the slug, or updates it (upsert). Check-ins carry release, environment and the trace of the code running ("DISTRIBUTED TRACING"), pass no hooks ("before_send" is for errors), and are rate limited and counted in client reports as data category monitor.

LOGS

"logger" sends logs, like sentry_sdk.logger of sentry-python: each linked to the trace and the active span, with attributes, and searchable in Sentry's Logs view. Calling it is the decision to send; the logging integrations send what the application logs only with "enable_logs". "before_send_log" filters and changes them.

Logs are not sent one by one but in batches of up to 100, as the official SDKs do. A batch is sent when it is full, when the next log comes 5 seconds or more after the first of the batch, when a request ends (the framework and server integrations; after the response, like events), at "flush" and "close", and when the process exits. Without a thread there is no timer: a script that idles keeps what it collected until one of these. A forked child does not send what its parent collected. Batches take the same way to Sentry as events (see "SENDING"); Sentry's rate limits for logs apply, discarded logs are counted in the client reports.

METRICS

"metrics" sends metric values: counters, gauges and distributions like sentry_sdk.metrics of sentry-python, linked to the trace and the active span like logs, and shown in Sentry's Metrics view. "before_send_metric" filters and changes them. They are sent in batches of up to 1000, at the same times as logs (see "LOGS"); Sentry's rate limits for metrics apply.

FUNCTIONS

init

Sentry::SDK->init(\%options);

Initializes the SDK: creates the client from the options below and sets up the integrations. Call it once, as early as possible: at the start of a script, in the startup file of a server (before it forks its workers), or let a framework plugin do it (Mojolicious::Plugin::SentrySDK, CGI::Application::Plugin::Sentry, Plack::Middleware::SentrySDK). Sentry::SDK::Manual shows the setup for each kind of application.

Calling init again replaces the client; the previous one is flushed and closed.

Options not given are read from SENTRY_* environment variables where noted; empty ones count as unset. Variables missing from %ENV, e.g. in a FastCGI request, whose parameters replace %ENV, are taken from the environment of the process as it was when the SDK was loaded: deleting one from %ENV does not unset it, setting it empty does.

Without a DSN, init says so in a CGI or FastCGI request (once per process), under mod_perl, and otherwise with "debug". An empty dsn option turns the SDK off without that message.

Invalid values are replaced by the default and unknown options are ignored, each with a warning (unknown ones once per process): a library loaded in production must not die over its configuration, unlike sentry-python, which raises an error. The client keeps the options it uses, see "get_options" in Sentry::Client.

The options by topic:

Basics

"dsn", "release", "environment", "dist", "server_name", "debug", "auto_session_tracking"

Errors

"sample_rate", "before_send", "ignore_errors", "attach_stacktrace", "include_source_context", "include_local_variables", "project_root", "in_app_include, in_app_exclude", "before_breadcrumb", "max_breadcrumbs", "max_attachment_size"

Tracing

"traces_sample_rate", "traces_sampler", "before_send_transaction", "ignore_transactions", "functions_to_trace", "max_spans", "enable_db_query_source, db_query_source_threshold_ms", "trace_propagation_targets", "org_id", "strict_trace_continuation", "enable_backpressure_handling"

Logs and metrics

"enable_logs", "before_send_log", "before_send_metric"

User feedback

"before_send_feedback"

Privacy

"send_default_pii", "denylist", "event_scrubber", "max_request_body_size", "record_sql_params"

Limits of event data

"max_value_length", "normalize_depth and normalize_max_breadth"

Integrations

"integrations", "default_integrations", "disabled_integrations"

Sending

"transport", "background_sender", "http_timeout", "shutdown_timeout", "transport_queue_size", "transport_compression_level", "send_client_reports", "http_proxy, https_proxy", "ca_certs"

dsn

Sentry::SDK->init({ dsn => 'https://<key>@<org>.ingest.sentry.io/<project>' });

Where to send the events, as shown in the project's settings in Sentry (Client Keys (DSN)). Defaults to the SENTRY_DSN environment variable. Without a DSN (and without "transport") the SDK captures and sends nothing; an empty string turns it off on purpose, without a warning.

release

The version of the application, e.g. a version number or a commit id, so that Sentry can tell in which release an error appeared and when it was fixed. Defaults to the SENTRY_RELEASE environment variable.

environment

A free-form name such as production or staging, to tell events of the same release in different deployments apart. Defaults to the SENTRY_ENVIRONMENT environment variable, else production.

dist

The distribution of the release, e.g. a build number, for releases that are built more than once. Unset by default.

auto_session_tracking

Whether the SDK sends sessions for "RELEASE HEALTH" on its own, of the program and of each web request. Default: 1, as in sentry-python. Sessions need a "release".

traces_sample_rate

Sentry::SDK->init({ traces_sample_rate => 0.2 });

A number between 0 and 1: the share of transactions that is sent (0.2: one in five). Setting it, or "traces_sampler", enables tracing; unset, no transaction is sent, but traces are still passed on (see "DISTRIBUTED TRACING"). Defaults to the SENTRY_TRACES_SAMPLE_RATE environment variable. A transaction continuing an incoming trace follows the caller's decision instead.

functions_to_trace

Sentry::SDK->init({
  functions_to_trace => [
    { qualified_name => 'My::Report::render' },
    { qualified_name => 'My::Mailer::send', op => 'mail.send' },
  ],
});

Functions to record a span for whenever they are called while a span is active, like sentry-python's option of that name: qualified_name, and optionally the op (default function) and description (default the qualified name) of the span. The span is the active one during the call, so spans of what the function does nest in it. Functions are wrapped at init, or once their package is loaded as a module; code references taken before init and packages defined later in files of another name are not traced, so call init early (see Sentry::Integration::FunctionsToTrace).

traces_sampler

Sentry::SDK->init({
  traces_sampler => sub ($context) {
    return 0 if ($context->{request}{url} // '') =~ m{/health\z};
    return $context->{parent_sampled} // 0.1;
  },
});

Decides per transaction with which rate it is sampled, like sentry-python's option of that name, and enables tracing. Called with the sampling context: transaction_context (name, op, source, origin, the ids and parent_sampled), parent_sampled (the decision of an incoming trace, if any), request (method, url and headers of a request the framework integrations serve, unscrubbed) and what was passed to "start_transaction". Returns a rate from 0 to 1 or a boolean; anything else, undef included, samples nothing with a warning, as does an error of the callback. Takes precedence over the decision of an incoming trace and "traces_sample_rate"; a transaction started with sampled keeps its decision.

enable_backpressure_handling

Sentry::SDK->init({ enable_backpressure_handling => 0 });

While the transport is unhealthy, transactions are sampled less, like sentry-python's option of that name: with the first transaction and then at most every 10 seconds, when a transaction starts, the SDK checks whether Sentry rate-limits transactions, spans or everything (unlike sentry-python, not a limit of other categories such as logs, which would sample traces down that Sentry still takes), sending is suspended after network errors (see "SENDING"), or envelopes pile up: the sender process has "transport_queue_size" of them waiting or its socket takes no more, or Mojo::IOLoop has as many requests pending as it takes. Each check that finds one of these halves the sample rate once more, down to 1/1024 of it; the first check that finds none restores it. The rate of "traces_sample_rate", of "traces_sampler" and of an incoming trace's decision is lowered alike. The dynamic sampling context carries the lowered rate, also an incoming one, unless the transaction follows the incoming decision, as in sentry-python; a transaction started with sampled keeps its decision. Transactions dropped that way, which the rate alone would have kept, are counted as backpressure in the client reports (see "send_client_reports"). Each process, also each worker a server forks, judges its own transport. Enabled by default; 0 samples as configured whatever the state of the transport. Custom transports report their health with "is_healthy" in Sentry::Transport.

send_default_pii

Set to a true value to send personal data with request data: cookies, the Cookie header, forwarding headers with client IPs, the headers with which authenticating proxies pass on the user (e.g. X-Forwarded-User, X-Amzn-Oidc-Data) and REMOTE_ADDR; and the ids and tokens in the keys of cache and Redis spans and breadcrumbs (e.g. session ids), which are * without. Disabled by default. Credentials (authorization headers, and parameters or headers whose names contain e.g. password, secret, token or session) are always replaced by [Filtered]. Of the process environment only SERVER_NAME and SERVER_PORT (and REMOTE_ADDR with this option) are sent.

Defaults to the SENTRY_SEND_DEFAULT_PII environment variable, which takes the words of sentry-python: true, t, yes, y, on or 1 and false, f, no, n, off or 0 (any case); init ignores other values with a warning. So one application of a host can send personal data without changing its code.

denylist

Sentry::SDK->init({ denylist => ['customer_id', qr/\Ainternal-/i] });

Further names of parameters, headers, cookies and keys whose values are always replaced by [Filtered], in addition to the built-in list (see Sentry::DataScrubber): in the request data, extra, user and the data of breadcrumbs and spans, also those the application sets; not in contexts and tags, as in sentry-python. Strings match names equal to them apart from case and separators, regexes are matched against the name. The session cookie of Mojolicious::Plugin::SentrySDK is filtered automatically.

event_scrubber

Sentry::SDK->init({
  event_scrubber => Sentry::DataScrubber->new(denylist => ['customer_id']),
});

What scrubs the data the application sets on events (extra, user, the data of breadcrumbs and spans, a request set on an event) before "before_send", like sentry-python's option of that name: an object with an event method (see "event" in Sentry::DataScrubber), which gets the event and returns the scrubbed copy. Defaults to a Sentry::DataScrubber with "denylist", "send_default_pii" and "max_request_body_size". A false value other than undef (e.g. 0) turns this scrubbing off; the request data the SDK collects is scrubbed anyway, by those options.

max_request_body_size

How much of a request body (form parameters, JSON) to send: never, small (up to 1000 bytes), medium (up to 10000 bytes, default) or always. Bodies above the limit are left out entirely.

record_sql_params

Set to a true value to record the bind values of SQL statements in breadcrumbs and spans of the DBI integration. Disabled by default, as bind values may contain credentials or personal data. Useful while debugging an issue.

enable_db_query_source, db_query_source_threshold_ms

Sentry::SDK->init({ db_query_source_threshold_ms => 50 });

Like sentry-python's options of these names: spans of database queries taking longer than db_query_source_threshold_ms (default 100) name the code of the application that ran them, the innermost frame of application code (see "in_app_include, in_app_exclude"), as code.filepath, code.lineno, code.function and code.namespace. Sentry's Queries insight shows it with the query. Enabled by default; set enable_db_query_source to 0 to disable it.

trace_propagation_targets

Sentry::SDK->init({
  trace_propagation_targets => ['api.example.com', qr{^https://internal\.}],
});

The outgoing HTTP integrations add the sentry-trace and baggage headers to requests, so that the receiving service can continue the trace (see "DISTRIBUTED TRACING"). This option limits them to URLs matching one of the given targets. A string is either a host (api.example.com, case-insensitive) or a URL prefix (https://example.com/api). A prefix matches URLs with the same scheme, host and port whose path is the prefix's path or below it (/api/v1, not /apis). A regex is matched against the whole URL. An empty list ([]) sends the headers nowhere.

By default the headers are added to all requests, as in sentry-python: third-party services the application calls (payment providers, public APIs) get them, too. They hold the trace id, the span id and the sampling decision, and in baggage the release, environment, organization id, public key of the DSN, transaction name (unless made from a URL) and sampling values of the service that started the trace; nothing about the user or the request. List your own services to keep that to them:

Sentry::SDK->init({
  trace_propagation_targets => [qr{^https://[^/]*\.example\.com/}],
});

Unlike in some other Sentry SDKs, strings are no substrings: as substring, api.example.com would also match https://elsewhere.example/?api.example.com and send trace ids to a third party. Use a regex for other matches.

org_id

Sentry::SDK->init({ org_id => '1234' });

The id of the Sentry organization. It defaults to the one in the host of a DSN of sentry.io (o1234.ingest.sentry.io); set it for a self-hosted Sentry. Incoming traces of another organization are not continued, as their ids and sampling decision mean nothing to this one.

strict_trace_continuation

Sentry::SDK->init({ strict_trace_continuation => 1 });

Also not continue incoming traces whose organization is unknown, or with an organization when this SDK knows none. Disabled by default.

project_root

Sentry::SDK->init({ project_root => '/srv/my-app' });

The application's directory: stack trace frames of files below it are application code, and their file names are sent relative to it. Defaults to the working directory at init; when Mojolicious::Plugin::SentrySDK initializes the SDK, to the application's home.

http_proxy, https_proxy

Sentry::SDK->init({ https_proxy => 'http://proxy.example.com:3128' });

The HTTP proxy to send through, as with sentry-python: an https DSN uses https_proxy, else http_proxy; a plain http DSN uses http_proxy. An empty string means no proxy. Unset, the proxy comes from the environment of the DSN's scheme: https_proxy or HTTPS_PROXY, http_proxy or HTTP_PROXY, then all_proxy or ALL_PROXY, unless no_proxy or NO_PROXY lists the Sentry host. In CGI requests clients can set HTTP_PROXY, so CGI_HTTP_PROXY takes its place, as in HTTP::Tiny; on Windows, whose environment ignores case, also that of http_proxy. Only http:// proxies are supported; others are ignored with a warning.

ca_certs

Sentry::SDK->init({ ca_certs => '/etc/ssl/my-ca.pem' });

A file of the certificates to trust for an https DSN, e.g. of the certificate authority of a self-hosted Sentry. Defaults to the certificates IO::Socket::SSL uses: SSL_CERT_FILE or SSL_CERT_DIR, else those of OpenSSL, else Mozilla::CA. If that is only a directory, sending without a running Mojo::IOLoop (with HTTP::Tiny) also trusts a bundle file: Mozilla::CA or the system's. Certificates are always verified.

http_timeout

Sentry::SDK->init({ http_timeout => 1 });

The seconds an event may take to be sent where the application waits for it (with HTTP::Tiny, see "flush"), from connecting through the TLS handshake to the response: default 2. Name resolution is not limited. A request taking longer counts as failed, and after repeated failures the SDK drops events for a while (see "SENDING") instead of letting an unreachable Sentry slow down every request. A slow but successful response is no failure, as in the official SDKs. Requests in the background of Mojo::IOLoop get generous timeouts instead (10 seconds to connect, 30 for the response), since a handler blocking the loop for a while must not make them fail.

transport_compression_level

Sentry::SDK->init({ transport_compression_level => 0 });

Envelopes of 30 KB or more are sent gzip-compressed (Content-Encoding: gzip) with this level, from 1 (fastest) to 9 (smallest); the default is zlib's 6. Smaller ones, the usual events, are sent as they are, like sentry-ruby does: Sentry mostly runs close to the applications, where compressing them would cost CPU time for nothing. 0 sends every envelope uncompressed.

send_client_reports

Sentry::SDK->init({ send_client_reports => 0 });

The SDK tells Sentry how many events, transactions and spans it dropped and why (sampling, "before_send", rate limits, network errors, full queues and others; see client reports), so that Sentry's statistics show them. The counts travel with the next envelope at most every 30 seconds, and on their own on "flush" and "close". Enabled by default; set to 0 to send none.

shutdown_timeout

Sentry::SDK->init({ shutdown_timeout => 5 });

The seconds the SDK waits at exit (and by default in "flush" and "close") for pending events to be sent, as in sentry-python: default 2. 0 does not wait; what is pending then is lost, with a warning.

transport_queue_size

The number of events waiting for the sender process, or held back during a request without one (see "SENDING"), as in sentry-python: default 100. Further events are dropped and counted as queue_overflow.

background_sender

Sentry::SDK->init({ background_sender => 0 });

Whether a process serving many requests hands its events to a sender process of its own instead of waiting for Sentry (see "SENDING"). Unset (the default), it does under PSGI servers and FastCGI loops; 1 also under mod_perl, and in the daemons of Mojolicious when their event loop cannot send. Like setting background_worker_threads to 0 in sentry-ruby, 0 sends every event in the process that captured it.

server_name

The name of the host, sent with every event. Defaults to the host name.

sample_rate

A number between 0 and 1: the share of error and message events that is sent. Defaults to 1 (all). Transactions are sampled with "traces_sample_rate".

in_app_include, in_app_exclude

Sentry::SDK->init({
  in_app_include => ['My::Shared'],
  in_app_exclude => ['My::App::Vendored'],
});

Stack trace frames are marked as application code (in_app) if their file lies below "project_root" and not in a library directory (perl's own, CPAN, local::lib or Carton's local/lib/perl5). These options override that for the given module name prefixes: My::Shared matches My::Shared and My::Shared::Util, but not My::SharedUtil. in_app_include takes precedence.

before_send

Sentry::SDK->init({
  before_send => sub ($event, $hint) {

    # discard event we don't care about
    if (ref($hint->{original_exception}) eq 'My::Ignorable::Exception') {
      return undef;
    }

    # add a custom tag otherwise
    $event->{tags}{foo} = 'bar';

    return $event;
  },
});

Called for error and message events immediately before they are sent, so it's the final place where you can edit their data. Return the (modified) event, or undef to drop it. For exceptions, $hint->{original_exception} holds the captured exception.

Without "before_send_transaction", before_send also gets transactions (type => 'transaction'), as in 1.x. This is deprecated and will be removed in 3.0: set before_send_transaction to handle transactions there, and before_send gets errors and messages only, as in the other Sentry SDKs.

$event->{contexts}{trace}{dynamic_sampling_context} is internal: the SDK moves it into the envelope header after the callback. A callback that replaces $event->{contexts}{trace} should keep it.

before_send_transaction

Sentry::SDK->init({
  before_send_transaction => sub ($transaction, $hint) {
    return undef if $transaction->{transaction} eq '/metrics';
    return $transaction;
  },
});

Called for transactions immediately before they are sent, after "ignore_transactions" and the event processors, like sentry-python's option of that name. Gets the transaction as it would be sent (a hash with type => 'transaction', transaction (the name), contexts (trace with op and status), spans, request, tags etc.) and the hint. Return it, changed or not, or undef to drop it. Spans removed from spans are dropped, too. Dropped transactions and spans are counted in the client reports (see "send_client_reports"); a callback that dies drops the transaction and is logged.

before_send_transaction => sub ($transaction, $hint) {
  # Keep only slow database queries
  $transaction->{spans} = [
    grep { $_->{op} ne 'db' || $_->{timestamp} - $_->{start_timestamp} > 0.1 }
      $transaction->{spans}->@*
  ];
  return $transaction;
},

To drop transactions by name, "ignore_transactions" is simpler; to send only some, use "traces_sampler", which decides before the transaction records anything. As with "before_send", $transaction->{contexts}{trace}{dynamic_sampling_context} is internal and must be kept.

before_send_feedback

Sentry::SDK->init({
  before_send_feedback => sub ($event, $hint) {
    delete $event->{contexts}{feedback}{contact_email};
    return $event;
  },
});

Like "before_send", but for feedback ("capture_feedback"), which before_send does not get.

before_send_log

Sentry::SDK->init({
  before_send_log => sub ($log, $hint) {
    return undef if $log->{level} eq 'debug';
    $log->{attributes}{tenant} = My::App->tenant;
    return $log;
  },
});

Called for each log (see "LOGS") before it is buffered for sending: return the (modified) log, or undef to drop it. The log has the fields timestamp, level (trace, debug, info, warn, error, fatal), severity_number, body, trace_id, span_id (while a span is active) and attributes, a hash of plain values; the hint is empty.

before_send_metric

Like "before_send_log", for metric values: they have the fields timestamp, type (counter, gauge, distribution), name, value, unit (if given), trace_id, span_id and attributes.

ignore_errors

Sentry::SDK->init({
  ignore_errors => ['My::NotFound', qr/^Client closed connection/],
});

Exceptions to drop: a string is a class name, matching exceptions of that class and its subclasses (or, for exceptions that are no objects, the reference type, e.g. HASH); a regex is matched against the exception message.

ignore_transactions

Sentry::SDK->init({
  ignore_transactions => ['/health', qr{^GET /static/}],
});

Transactions to drop by name. As in other Sentry SDKs, strings are regexes matching the end of the name (/health drops GET /health); pass qr// objects for other matches.

before_breadcrumb

Sentry::SDK->init({
  before_breadcrumb => sub ($breadcrumb, $hint) {
    return undef if ($breadcrumb->{category} // '') eq 'query';
    return $breadcrumb;
  },
});

Called for every breadcrumb before it is added to the scope, with the hint given to "add_breadcrumb". Return the (modified) breadcrumb, or undef to drop it.

max_breadcrumbs

The number of breadcrumbs kept per scope and attached to an event (the newest of all scopes in effect), default 100 or the value of the SENTRY_MAX_BREADCRUMBS environment variable. Breadcrumbs are attached to errors and messages, not to transactions.

max_spans

The maximum number of child spans recorded per transaction, default 1000. Further spans work, but are not sent.

max_value_length

Strings in events are cut after this many characters, default 8192: messages, exception values, breadcrumbs (e.g. SQL statements), span descriptions and data, request data (e.g. header values), contexts, extra data and the user. 0 disables the limit, except for exception values, which are always cut at 65,536 characters. Tag values are always limited to 200 characters.

normalize_depth and normalize_max_breadth

Limits for the data of contexts, extra, user, request and breadcrumbs: structures deeper than normalize_depth levels (default 10) are replaced by [Object] or [Array], only the first normalize_max_breadth (default 1000) keys or items are kept. Reference cycles are broken, objects are sent as the result of their TO_JSON method or as string.

attach_stacktrace

Messages ("capture_message") get the stack trace of the place they were captured at. Disabled by default, as in the official SDKs: Sentry groups messages by their text then, otherwise by the stack trace.

enable_logs

What the application logs with Mojo::Log or Log::Log4perl is sent as Sentry logs as well (see "LOGS"), from the logs_level of the logging integration on (default info, see "logs_level" in Sentry::Integration::Logging). Off by default: logs count against a quota of their own, and an application may log a lot. Logs sent with "logger" do not need it.

max_attachment_size

Attachments (Sentry::Attachment) larger than this many bytes are not sent, default 20 MiB.

include_source_context

Stack trace frames carry the surrounding lines of source code. Enabled by default. Only Perl files (.pm, .pl, .t, .cgi, .fcgi, .psgi, .plx, and files without extension starting with a perl shebang line) and templates (.ep, .mt, .tt, .tt2, .tmpl, .tx) of up to 1 MB are read; file names in stack traces can be set by code (#line) and must not make the SDK send arbitrary files. Set to 0 to send no source code to Sentry.

include_local_variables

Stack trace frames of exceptions carry the values of the lexical (my) variables in scope where the exception was thrown, like sentry-python's option of that name; in a named subroutine, the lexicals of the file only if it uses them. Enabled by default; it needs PadWalker, a dependency of the SDK, and frames carry no variables should it fail to load. Set to 0 to send none.

Frames taken where an event is captured carry them as well: those of messages with "attach_stacktrace", and those of an exception that was never thrown where the die handler saw it ("capture_exception" takes the stack of its caller then), as in sentry-python. These frames are still live, their values are taken right then, within the same limits.

Perl unwinds the frames before an exception can be captured, so the values are taken when it is thrown, by the die handler (see Sentry::Integration::DieHandler), and copied right away, so that no object lives longer because of it. That happens at every die, also of exceptions caught right away, which bounds the work:

  • Up to 5 frames per exception, application code (see "in_app_include, in_app_exclude") first, the innermost first; never those of the SDK.

  • Up to 10 variables per frame, and 10 keys or items per structure, 5 levels deep, at most 50 values per frame; strings are cut after 1024 characters. Objects are sent as their string, without calling TO_JSON: an object overloading "" as that string, others as Class=HASH(0x...). No other overload is called (through fallback, stringifying a DBIx::Class::ResultSet would count its rows in the database). Tied variables and hashes a loop iterates over with each are not looked into.

  • Variables are taken for up to 50 stacks (exceptions or captured events) per second and process; the frames of further ones carry none. A rethrown exception keeps the variables of its first throw.

The values are scrubbed like the other data of the event (see "denylist"): $password or the Authorization key of %headers are sent as [Filtered].

integrations

Sentry::SDK->init({
  integrations => [My::Integration->new],
});

Adds custom integrations and configures the default ones: an instance of a default integration class replaces the default instance.

Sentry::SDK->init({
  integrations => [Sentry::Integration::DBI->new(breadcrumbs => 0)],
});

Integrations instrument a module once it is loaded, regardless of whether it is loaded before or after init. They never load modules themselves. Their constructors die on unknown arguments, so a misspelt one is noticed.

default_integrations

Sentry::SDK->init({ default_integrations => 0 });

Set to a false value to skip the integrations that are enabled by default (see "INTEGRATIONS"), including the die handler that reports uncaught exceptions. Custom "integrations" are enabled nevertheless.

Integrations patch code process-wide and only once, but a patched call is only recorded while the current client has the integration enabled. An init with other integration options therefore takes effect.

disabled_integrations

Sentry::SDK->init({
  disabled_integrations => ['Sentry::Integration::Redis'],
});

Integrations not to use, as class names or instances, like sentry-python's option of that name: e.g. one default integration, keeping the others. A class that is neither an integration of the SDK nor one of "integrations" (e.g. misspelt) is ignored with a warning.

transport

Sentry::SDK->init({ transport => Sentry::Transport::Memory->new });

The Sentry::Transport that delivers the envelopes: an instance, or the name of a class, which is loaded and created with from_options by init (if that dies, init warns and the SDK stays off). Defaults to Sentry::Transport::Http. With a transport given, the SDK captures events also without "dsn", e.g. into Sentry::Transport::Memory; tests of an application use Sentry::Test, which does that for every init.

debug

Enables debug printing of all contexts to STDERR.

Debug printing can also be enabled with the SENTRY_DEBUG environment variable: SENTRY_DEBUG=1 enables all contexts, a comma separated list of context names only the matching ones, * works as wildcard (e.g. SENTRY_DEBUG=Tracing,Sentry::Transport::*). The debug option takes precedence and enables all contexts.

add_breadcrumb

Sentry::SDK->add_breadcrumb({
  category => "auth",
  message => "Authenticated user " . user->{email},
  level => Sentry::Severity->Info,
});

Sentry::SDK->add_breadcrumb(\%breadcrumb, \%hint);

Adds the breadcrumb to the isolation scope. The optional hint is passed to "before_breadcrumb".

You can manually add breadcrumbs whenever something interesting happens. For example, you might manually record a breadcrumb if the user authenticates or another state change happens.

add_feature_flag

my $enabled = $flags->is_enabled('new-checkout');
Sentry::SDK->add_feature_flag('new-checkout' => $enabled);

Records the result of a feature flag evaluation, like sentry_sdk.feature_flags.add_feature_flag of sentry-python: call it wherever the application evaluates a flag. Sentry shows the flags of an error in its Feature Flags section and can tell which flags errors come with.

The result is recorded in the isolation scope, which keeps the 100 flags evaluated last (see Sentry::FeatureFlags); the errors and messages captured in the request or job carry them as flags context (transactions do not, as in sentry-python). The active span, if any, gets the data flag.evaluation.new-checkout, for the first 10 flags evaluated in it (see "set_flag" in Sentry::Tracing::Span).

Sentry knows boolean flags only: the result is taken by Perl's truth, 0, '' and undef are false, everything else (also the string 'off') is true. Record flags of other types (variants, numbers) as tags ("set_tag, set_tags"), or a boolean of your own, e.g. $variant eq 'b'.

capture_exception

eval {
  $app->run();
};
if ($@) {
  Sentry::SDK->capture_exception($@);
}

You can pass an error object to capture_exception() to get it captured as event. It's possible to throw strings as errors.

Stack traces are taken from the exception if it carries one: Mojo::Exception, Exception::Class, Throwable with StackTrace::Auto and others providing a Devel::StackTrace via trace or stack_trace. String exceptions get the stack trace recorded by the die handler integration, others the one of the capture_exception call. Exceptions found via cause, previous or previous_exception are reported as chained exceptions.

Exceptions nobody catches, which end the program, are captured automatically (see Sentry::Integration::DieHandler).

All capture_* functions return the id of the event, or undef if it was not sent (no DSN, dropped by sampling, "ignore_errors", "before_send" or an event processor, or an error inside the SDK).

last_event_id

my $event_id = Sentry::SDK->last_event_id;

The id of the last error or message event sent in the current isolation scope (i.e. by this request; transactions don't count), e.g. to show it to the user. undef if none was sent.

capture_message

Sentry::SDK->capture_message("Something went wrong");

Another common operation is to capture a bare message. A message is textual information that should be sent to Sentry. Typically messages are not emitted, but they can be useful for some teams.

capture_event

Sentry::SDK->capture_event(\%data);

Captures a manually created event and sends it to Sentry.

capture_feedback

my $event_id = Sentry::SDK->capture_feedback({
  message             => 'The checkout button does nothing',
  name                => 'Jane Doe',
  email               => 'jane@example.com',
  url                 => 'https://example.com/checkout',
  associated_event_id => Sentry::SDK->last_event_id,
});

Sends feedback of a user, e.g. from a feedback form, which Sentry shows under User Feedback and with the event of associated_event_id. Only message is required; it is cut at 4096 characters. Feedback gets the data of the scopes, their attachments, and those of the optional hint:

Sentry::SDK->capture_feedback({ message => $text },
  { attachments => [{ bytes => $screenshot, filename => 'screen.png' }] });

It is neither sampled nor passed to "before_send", but to "before_send_feedback". Returns the event id, undef if nothing was sent; "last_event_id" stays as it is.

logger

Sentry::SDK->logger->info('Order %s placed', [$order_id],
  { 'order.items' => 3 });

The logger sending structured logs to Sentry, see Sentry::Logs and "LOGS".

metrics

Sentry::SDK->metrics->count('order.placed');
Sentry::SDK->metrics->distribution('order.value', $total,
  { unit => 'euro' });

Sends metrics to Sentry, see Sentry::Metrics and "METRICS".

configure_scope

Sentry::SDK->configure_scope(sub ($scope) {
  $scope->set_tag(foo => "bar");
  $scope->set_user({id => 1, email => "john.doe@example.com"});
});

Passes the isolation scope to the callback, i.e. the data applies to the whole request or job, not only to the innermost "with_scope" block. See "SCOPES" and Sentry::Scope.

set_tag, set_tags

Sentry::SDK->set_tag(page_locale => 'de-at');
Sentry::SDK->set_tags({ page_locale => 'de-at', tenant => 'acme' });

Sets tags on the isolation scope. Tags are indexed by Sentry and can be searched and filtered by.

set_extra, set_extras

Sentry::SDK->set_extra(order => { id => 42, items => 3 });
Sentry::SDK->set_extras({ order => { id => 42 }, cart => [...] });

Sets additional data on the isolation scope. It is not indexed.

set_context

Sentry::SDK->set_context(character => { name => 'Mighty Fighter', level => 19 });
Sentry::SDK->set_context(character => undef);    # removes it

Sets (or, with undef, removes) a named context on the isolation scope.

set_user

Sentry::SDK->set_user({ id => 42, username => 'jane' });

Sets the user on the isolation scope. Mind your privacy obligations.

set_level

Sentry::SDK->set_level(Sentry::Severity->Warning);

Sets the level of all events captured in the isolation scope.

set_transaction_name

Sentry::SDK->set_transaction_name('GET ' . ref $page);
Sentry::SDK->set_transaction_name('checkout', 'view');

Renames the transaction of the request (or job), with the source custom unless given (see the sources), and gives errors captured in the isolation scope the same name. The framework integrations keep a custom name. Same as Sentry::SDK->get_isolation_scope->set_transaction_name, see "set_transaction_name" in Sentry::Scope.

with_scope

Sentry::SDK->with_scope(sub ($scope) {
  $scope->set_tag(batch => $batch_id);
  Sentry::SDK->capture_message('batch failed');
});

Runs the callback with a clone of the current scope as current scope, so that changes don't outlive the callback. Returns the callback's result and rethrows its exceptions.

Top-level functions such as "set_tag, set_tags" write to the isolation scope, so their data outlives the block; change the scope given to the callback instead.

$scope->clear_breadcrumbs on the given scope also hides the breadcrumbs the global and isolation scope hold at that moment from events captured in the block: the event gets no breadcrumb added before, but those added afterwards to any scope.

with_isolation_scope

Sentry::SDK->with_isolation_scope(sub ($scope) {
  Sentry::SDK->set_user({ id => $job->user_id });
  $job->run;
});

Runs the callback with clones of the isolation and the current scope, e.g. for a job of a worker process. The callback gets the isolation scope. Returns the callback's result and rethrows its exceptions.

get_global_scope, get_isolation_scope, get_current_scope

Sentry::SDK->get_isolation_scope->set_tag(tenant => 'acme');

The scopes in effect, see "SCOPES" and Sentry::Scope.

get_client

my $client = Sentry::SDK->get_client;

The client of the current scope, else of the isolation scope, else of the global scope, where "init" puts it. Never undef: before "init" and without DSN it is a Sentry::Client::NoOp, which sends nothing. Its options are readable with Sentry::SDK->get_client->get_options (see Sentry::Options).

get_current_span

my $span = Sentry::SDK->get_current_span;
my $child = $span && $span->start_child({ op => 'task' });

The span (or transaction) of the current scope, else of the isolation or global scope, if any.

start_transaction

my $transaction = Sentry::SDK->start_transaction({
  name => 'MyScript',
  op => 'http.server',
});

Sentry::SDK->get_current_scope->set_span($transaction);

# ...

$transaction->set_http_status(200);
$transaction->finish();

Is needed for recording tracing information. Transactions are usually handled by the respective framework integration. See Sentry::Tracing::Transaction.

A transaction without trace_id joins the trace the isolation scope continues (see "continue_trace"), otherwise it starts a trace of its own. It is sampled with the caller's sampling decision if there is one, else with "traces_sample_rate".

start_span

my $span = Sentry::SDK->start_span({ op => 'task', name => 'resize images' });
...;
$span->finish;

Starts a span for code of the application, like sentry-python's start_span: a child of the active span (see "get_current_span"), with the name as its description, or a transaction of that name if no span is active. Takes a hash reference, like "start_transaction"; further keys are those of "start_child" in Sentry::Tracing::Span or "start_transaction". Its origin is manual. The span does not become the active one: to nest spans in it, set it with Sentry::SDK->get_current_scope->set_span inside "with_scope".

continue_trace

my $result = Sentry::SDK->continue_trace(
  { 'sentry-trace' => $message->{sentry_trace}, baggage => $message->{baggage} },
  sub ($scope) {
    my $transaction = Sentry::SDK->start_transaction(
      { name => 'process message', op => 'queue.process' });
    Sentry::SDK->get_current_scope->set_span($transaction);
    ...;
    $transaction->finish;
  }
);

Runs the callback in a new isolation scope (see "with_isolation_scope") that continues the trace of the given sentry-trace and baggage header values. Header names are case-insensitive; CGI variable names (HTTP_SENTRY_TRACE) work as well, so \%ENV of a CGI request will do. Without valid sentry-trace the callback runs in a new trace. Transactions started in the callback without trace_id join the trace: the caller's span is their parent and its sampling decision theirs. Errors captured in the callback belong to the trace, too. Returns the callback's result and rethrows its exceptions.

Requests of the framework integrations do this on their own.

get_traceparent, get_baggage

my $sentry_trace = Sentry::SDK->get_traceparent;
my $baggage      = Sentry::SDK->get_baggage;

The values of the sentry-trace and baggage headers that continue the current trace: of the active span while tracing is enabled, else of the trace of the isolation scope. For custom clients and messages, or the meta tags of a browser SDK (<meta name="sentry-trace"> and <meta name="baggage">). undef without client.

flush

my $all_sent = Sentry::SDK->flush($timeout);

Sends what is pending within $timeout seconds (default: "shutdown_timeout"): the events held back during a request, the client reports, and the events sent in the background, by the sender process or by Mojo::IOLoop. Returns whether all of them were sent (or dropped, e.g. by rate limits, which client reports count). This happens automatically when the process exits normally.

flush runs the event loop to wait for background requests, i.e. other events of the loop are processed meanwhile; at exit, callbacks of timers and requests of the application no longer run (see Sentry::Integration::MojoIOLoop). It can't wait while the loop is running (inside a callback) and returns false immediately if events are pending then. A forked child does not wait for events of its parent. Events are sent in the background only once the loop has iterated in the current process (or the Mojolicious plugin dispatches a request), so that a child forked inside a running loop, which inherits its "running" state, does not lose them.

close

Sentry::SDK->close($timeout);

Like "flush", but disables the client afterwards: nothing is captured anymore until the next "init".

capture_check_in

my $check_in_id = Sentry::SDK->capture_check_in(
  { monitor_slug => 'nightly-report', status => 'in_progress' },
  \%monitor_config,
);
...;
Sentry::SDK->capture_check_in({
  monitor_slug => 'nightly-report',
  check_in_id  => $check_in_id,
  status       => 'ok',           # or 'error'
  duration     => $seconds,
});

Sends a check-in (see "CRON MONITORING") and returns its id (a new one unless given), or undef if it was not sent, e.g. without DSN. The optional monitor configuration, best sent with in_progress only, has the keys of monitor_config: schedule (required: { type => 'crontab', value => '0 2 * * *' } or { type => 'interval', value => 2, unit => 'hour' }, units year, month, week, day, hour, minute), checkin_margin and max_runtime (minutes), failure_issue_threshold and recovery_threshold (check-ins), timezone (e.g. Europe/Berlin) and owner (e.g. team:backend); checkin_margin, max_runtime and the thresholds are positive integers. Invalid arguments are not sent: the SDK warns, naming the caller, also without DSN, but does not die. trace_id is set by the SDK.

monitor

my $result = Sentry::SDK->monitor($monitor_slug, sub { ... }, \%monitor_config);

Like sentry-python's monitor: checks in in_progress (with the optional monitor configuration, see "capture_check_in"), runs the code, then checks in ok, or error if the code died, with the duration. Invalid arguments only cost the check-ins (with a warning): the code runs anyway. Returns what the code returns (in the context of the call) and rethrows what it died with.

start_session, end_session

Sentry::SDK->end_session;      # e.g. before a long idle phase
Sentry::SDK->start_session;

End the session of the program (as exited, unless it crashed) and start a new one, ending the current one first. For long running programs whose work comes in phases, see "RELEASE HEALTH"; "init" starts the first one.

AUTHOR

Philipp Busse <pmb@heise.de>

COPYRIGHT

Copyright 2021- Philipp Busse

LICENSE

This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.

SEE ALSO

Sentry::SDK::Manual, Sentry's documentation, Sentry's SDK development guide.