# 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](https://sentry.io), following the behavior of
Sentry's official SDKs.

This is the reference of the API and the options. [Sentry::SDK::Manual](https://metacpan.org/pod/Sentry%3A%3ASDK%3A%3AManual)
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](https://github.com/heiseonline/perl-sentry-sdk/blob/master/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](https://develop.sentry.dev/sdk/telemetry/scopes/)),
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"](#with_isolation_scope)). ["set\_tag, set\_tags"](#set_tag-set_tags), ["set\_user"](#set_user),
    ["add\_breadcrumb"](#add_breadcrumb), ["add\_feature\_flag"](#add_feature_flag), ["configure\_scope"](#configure_scope) etc. write here.
    It also holds the id of the last event (["last\_event\_id"](#last_event_id)) and the trace
    that errors outside of transactions are linked by.

- current scope

    One per block of code (["with\_scope"](#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_scope),
["with\_isolation\_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](https://metacpan.org/pod/Mojo%3A%3APromise), [Mojo::IOLoop](https://metacpan.org/pod/Mojo%3A%3AIOLoop) timers and
non-blocking [Mojo::UserAgent](https://metacpan.org/pod/Mojo%3A%3AUserAgent) requests take the scopes along (see
[Sentry::Integration::MojoIOLoop](https://metacpan.org/pod/Sentry%3A%3AIntegration%3A%3AMojoIOLoop)), as do those of [AnyEvent](https://metacpan.org/pod/AnyEvent) (see
[Sentry::Integration::AnyEvent](https://metacpan.org/pod/Sentry%3A%3AIntegration%3A%3AAnyEvent)) and [AnyEvent::HTTP](https://metacpan.org/pod/AnyEvent%3A%3AHTTP) requests; for
others use ["bind\_scopes" in Sentry::Scope](https://metacpan.org/pod/Sentry%3A%3AScope#bind_scopes).

# 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](https://develop.sentry.dev/sdk/foundations/trace-propagation/)):

- outgoing requests

    [HTTP::Tiny](https://metacpan.org/pod/HTTP%3A%3ATiny), [LWP::UserAgent](https://metacpan.org/pod/LWP%3A%3AUserAgent), [Mojo::UserAgent](https://metacpan.org/pod/Mojo%3A%3AUserAgent) and [AnyEvent::HTTP](https://metacpan.org/pod/AnyEvent%3A%3AHTTP)
    requests carry the `sentry-trace` and `baggage` headers (see
    ["trace\_propagation\_targets"](#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"](#init) on, e.g. a job run by a traced service. Commands run with
    backticks, [IPC::Open2](https://metacpan.org/pod/IPC%3A%3AOpen2), [IPC::Open3](https://metacpan.org/pod/IPC%3A%3AOpen3) or [IPC::Cmd](https://metacpan.org/pod/IPC%3A%3ACmd) get them from
    [Sentry::Integration::Subprocess](https://metacpan.org/pod/Sentry%3A%3AIntegration%3A%3ASubprocess).

- other units of work

    Messages of a job queue and the like continue a trace with
    ["continue\_trace"](#continue_trace); ["get\_traceparent, get\_baggage"](#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"](#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"](#traces_sample_rate)), a service still passes the trace on, and its
errors are linked to it.

The [dynamic sampling context](https://develop.sentry.dev/sdk/telemetry/traces/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"](#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](https://metacpan.org/pod/Plack%3A%3AMiddleware%3A%3ASentrySDK) (unless the server runs the
application once, as [Plack::Handler::CGI](https://metacpan.org/pod/Plack%3A%3AHandler%3A%3ACGI) does), also with the
Mojolicious plugin or [CGI::Application](https://metacpan.org/pod/CGI%3A%3AApplication) served by a PSGI server, and
with a FastCGI loop ([Sentry::Integration::FCGI](https://metacpan.org/pod/Sentry%3A%3AIntegration%3A%3AFCGI)); each of them tells the SDK when it starts
serving a request. Under mod\_perl ([Sentry::Integration::ModPerl](https://metacpan.org/pod/Sentry%3A%3AIntegration%3A%3AModPerl)) events
are sent in the cleanup phase after the response instead, unless
["background\_sender"](#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](https://metacpan.org/pod/HTTP%3A%3ATiny) and [IO::Socket::SSL](https://metacpan.org/pod/IO%3A%3ASocket%3A%3ASSL), 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"](#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"](#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"](#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"](#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](https://metacpan.org/pod/HTTP%3A%3ATiny),
and the application waits for the response, at most ["http\_timeout"](#http_timeout)
seconds. Inside a running [Mojo::IOLoop](https://metacpan.org/pod/Mojo%3A%3AIOLoop) of an application using
Mojolicious (its daemons, also preforking ones), they are sent in the
background of the loop with [Mojo::UserAgent](https://metacpan.org/pod/Mojo%3A%3AUserAgent) 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](https://metacpan.org/pod/CGI%3A%3AApplication%3A%3APlugin%3A%3ASentry) or [Plack::Middleware::SentrySDK](https://metacpan.org/pod/Plack%3A%3AMiddleware%3A%3ASentrySDK))
are held back and sent when the response is complete, at most
["transport\_queue\_size"](#transport_queue_size) of them. No request is started after
["http\_timeout"](#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"](#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"](#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"](#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"](#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"](#enable_backpressure_handling)).

For tests of an application, [Sentry::Test](https://metacpan.org/pod/Sentry%3A%3ATest) 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"](#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"](#integrations),
["disabled\_integrations"](#disabled_integrations) and ["default\_integrations"](#default_integrations) to configure them.

Web frameworks and servers:

- [Mojolicious::Plugin::SentrySDK](https://metacpan.org/pod/Mojolicious%3A%3APlugin%3A%3ASentrySDK)

    Plugin for [Mojolicious](https://metacpan.org/pod/Mojolicious) applications.

- [CGI::Application::Plugin::Sentry](https://metacpan.org/pod/CGI%3A%3AApplication%3A%3APlugin%3A%3ASentry), [Sentry::Integration::CGIApplication](https://metacpan.org/pod/Sentry%3A%3AIntegration%3A%3ACGIApplication)

    Every [CGI::Application](https://metacpan.org/pod/CGI%3A%3AApplication) (default; the plugin adds initialization from
    the application's parameters).

- [Plack::Middleware::SentrySDK](https://metacpan.org/pod/Plack%3A%3AMiddleware%3A%3ASentrySDK)

    Middleware for PSGI applications.

- [Sentry::Integration::FCGI](https://metacpan.org/pod/Sentry%3A%3AIntegration%3A%3AFCGI)

    FastCGI loops of [FCGI](https://metacpan.org/pod/FCGI) and [CGI::Fast](https://metacpan.org/pod/CGI%3A%3AFast) (default).

- [Sentry::Integration::CGI](https://metacpan.org/pod/Sentry%3A%3AIntegration%3A%3ACGI)

    The request of a CGI script (default).

- [Sentry::Integration::ModPerl](https://metacpan.org/pod/Sentry%3A%3AIntegration%3A%3AModPerl)

    Every request of a mod\_perl 2 server (default).

- [Sentry::Integration::NetServer](https://metacpan.org/pod/Sentry%3A%3AIntegration%3A%3ANetServer)

    The parent of a preforking [Net::Server](https://metacpan.org/pod/Net%3A%3AServer), 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](https://metacpan.org/pod/Sentry%3A%3AIntegration%3A%3ADBI)

    Statements, transactions and connections of [DBI](https://metacpan.org/pod/DBI).

- [Sentry::Integration::DBIxClass](https://metacpan.org/pod/Sentry%3A%3AIntegration%3A%3ADBIxClass)

    The result sources of [DBIx::Class](https://metacpan.org/pod/DBIx%3A%3AClass) statements, on the spans of the DBI
    integration, and its transactions (`txn_do`) and savepoints.

- [Sentry::Integration::MongoDB](https://metacpan.org/pod/Sentry%3A%3AIntegration%3A%3AMongoDB)

    Commands of the official [MongoDB](https://metacpan.org/pod/MongoDB) driver.

- [Sentry::Integration::Elasticsearch](https://metacpan.org/pod/Sentry%3A%3AIntegration%3A%3AElasticsearch)

    Requests of [Search::Elasticsearch](https://metacpan.org/pod/Search%3A%3AElasticsearch).

- [Sentry::Integration::NetLDAP](https://metacpan.org/pod/Sentry%3A%3AIntegration%3A%3ANetLDAP)

    Operations of [Net::LDAP](https://metacpan.org/pod/Net%3A%3ALDAP).

- [Sentry::Integration::Redis](https://metacpan.org/pod/Sentry%3A%3AIntegration%3A%3ARedis)

    Commands of [Redis](https://metacpan.org/pod/Redis) and [Redis::Fast](https://metacpan.org/pod/Redis%3A%3AFast).

- [Sentry::Integration::CacheMemcached](https://metacpan.org/pod/Sentry%3A%3AIntegration%3A%3ACacheMemcached)

    Operations of [Cache::Memcached](https://metacpan.org/pod/Cache%3A%3AMemcached).

- [Sentry::Integration::LwpUserAgent](https://metacpan.org/pod/Sentry%3A%3AIntegration%3A%3ALwpUserAgent)

    Requests of [LWP::UserAgent](https://metacpan.org/pod/LWP%3A%3AUserAgent) (and [LWP::Simple](https://metacpan.org/pod/LWP%3A%3ASimple), [WWW::Mechanize](https://metacpan.org/pod/WWW%3A%3AMechanize)).

- [Sentry::Integration::MojoUserAgent](https://metacpan.org/pod/Sentry%3A%3AIntegration%3A%3AMojoUserAgent)

    Requests of [Mojo::UserAgent](https://metacpan.org/pod/Mojo%3A%3AUserAgent).

- [Sentry::Integration::AnyEventHTTP](https://metacpan.org/pod/Sentry%3A%3AIntegration%3A%3AAnyEventHTTP)

    Requests of [AnyEvent::HTTP](https://metacpan.org/pod/AnyEvent%3A%3AHTTP).

- [Sentry::Integration::GraphQLClient](https://metacpan.org/pod/Sentry%3A%3AIntegration%3A%3AGraphQLClient)

    Requests of [GraphQL::Client](https://metacpan.org/pod/GraphQL%3A%3AClient): the operation on the span of its HTTP
    request, a request that failed on the events of the unit of work.

- [Sentry::Integration::NetApnsSimple](https://metacpan.org/pod/Sentry%3A%3AIntegration%3A%3ANetApnsSimple)

    Push notifications sent with [Net::APNS::Simple](https://metacpan.org/pod/Net%3A%3AAPNS%3A%3ASimple).

- [Sentry::Integration::MojoTemplate](https://metacpan.org/pod/Sentry%3A%3AIntegration%3A%3AMojoTemplate)

    Rendering of [Mojo::Template](https://metacpan.org/pod/Mojo%3A%3ATemplate).

- [Sentry::Integration::TemplateToolkit](https://metacpan.org/pod/Sentry%3A%3AIntegration%3A%3ATemplateToolkit)

    Rendering of [Template](https://metacpan.org/pod/Template) (Template Toolkit).

- [Sentry::Integration::HttpTiny](https://metacpan.org/pod/Sentry%3A%3AIntegration%3A%3AHttpTiny)

    Requests of [HTTP::Tiny](https://metacpan.org/pod/HTTP%3A%3ATiny), other than the SDK's own.

- [Sentry::Integration::SoapLite](https://metacpan.org/pod/Sentry%3A%3AIntegration%3A%3ASoapLite)

    Calls of [SOAP::Lite](https://metacpan.org/pod/SOAP%3A%3ALite).

- [Sentry::Integration::NetFTP](https://metacpan.org/pod/Sentry%3A%3AIntegration%3A%3ANetFTP)

    Commands of [Net::FTP](https://metacpan.org/pod/Net%3A%3AFTP).

- [Sentry::Integration::NetSMTP](https://metacpan.org/pod/Sentry%3A%3AIntegration%3A%3ANetSMTP)

    Commands of [Net::SMTP](https://metacpan.org/pod/Net%3A%3ASMTP).

- [Sentry::Integration::MIMELite](https://metacpan.org/pod/Sentry%3A%3AIntegration%3A%3AMIMELite)

    Messages sent with [MIME::Lite](https://metacpan.org/pod/MIME%3A%3ALite).

- [Sentry::Integration::HTMLTemplate](https://metacpan.org/pod/Sentry%3A%3AIntegration%3A%3AHTMLTemplate)

    Parsing and rendering of [HTML::Template](https://metacpan.org/pod/HTML%3A%3ATemplate).

- [Sentry::Integration::HTMLTemplatePro](https://metacpan.org/pod/Sentry%3A%3AIntegration%3A%3AHTMLTemplatePro)

    Rendering of [HTML::Template::Pro](https://metacpan.org/pod/HTML%3A%3ATemplate%3A%3APro).

- [Sentry::Integration::LibXSLT](https://metacpan.org/pod/Sentry%3A%3AIntegration%3A%3ALibXSLT)

    Stylesheets of [XML::LibXSLT](https://metacpan.org/pod/XML%3A%3ALibXSLT).

- [Sentry::Integration::ImageMagick](https://metacpan.org/pod/Sentry%3A%3AIntegration%3A%3AImageMagick)

    Reading, writing and processing images with [Image::Magick](https://metacpan.org/pod/Image%3A%3AMagick) and
    `Graphics::Magick`.

- [Sentry::Integration::NetAmazonS3](https://metacpan.org/pod/Sentry%3A%3AIntegration%3A%3ANetAmazonS3)

    Operations of [Net::Amazon::S3](https://metacpan.org/pod/Net%3A%3AAmazon%3A%3AS3) and [Net::Amazon::S3::Client](https://metacpan.org/pod/Net%3A%3AAmazon%3A%3AS3%3A%3AClient).

- [Sentry::Integration::ArchiveZip](https://metacpan.org/pod/Sentry%3A%3AIntegration%3A%3AArchiveZip)

    Reading, writing and extracting archives with [Archive::Zip](https://metacpan.org/pod/Archive%3A%3AZip).

Logging (default, see [Sentry::Integration::Logging](https://metacpan.org/pod/Sentry%3A%3AIntegration%3A%3ALogging)):

- [Sentry::Integration::MojoLog](https://metacpan.org/pod/Sentry%3A%3AIntegration%3A%3AMojoLog)

    Messages of [Mojo::Log](https://metacpan.org/pod/Mojo%3A%3ALog).

- [Sentry::Integration::Log4perl](https://metacpan.org/pod/Sentry%3A%3AIntegration%3A%3ALog4perl)

    Messages of [Log::Log4perl](https://metacpan.org/pod/Log%3A%3ALog4perl).

Runtime (default):

- [Sentry::Integration::DieHandler](https://metacpan.org/pod/Sentry%3A%3AIntegration%3A%3ADieHandler)

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

- [Sentry::Integration::MojoIOLoop](https://metacpan.org/pod/Sentry%3A%3AIntegration%3A%3AMojoIOLoop)

    Scopes of callbacks of [Mojo::IOLoop](https://metacpan.org/pod/Mojo%3A%3AIOLoop), [Mojo::Promise](https://metacpan.org/pod/Mojo%3A%3APromise) and non-blocking
    [Mojo::UserAgent](https://metacpan.org/pod/Mojo%3A%3AUserAgent) requests, and their errors.

- [Sentry::Integration::AnyEvent](https://metacpan.org/pod/Sentry%3A%3AIntegration%3A%3AAnyEvent)

    Scopes of callbacks of [AnyEvent](https://metacpan.org/pod/AnyEvent) watchers, condition variables,
    [AnyEvent::Handle](https://metacpan.org/pod/AnyEvent%3A%3AHandle) and [AnyEvent::DNS](https://metacpan.org/pod/AnyEvent%3A%3ADNS), with any backend.

- [Sentry::Integration::FunctionsToTrace](https://metacpan.org/pod/Sentry%3A%3AIntegration%3A%3AFunctionsToTrace)

    Spans for the functions of ["functions\_to\_trace"](#functions_to_trace) (enabled by that option).

- [Sentry::Integration::Subprocess](https://metacpan.org/pod/Sentry%3A%3AIntegration%3A%3ASubprocess)

    Commands run with backticks, `qx//`, [IPC::Open2](https://metacpan.org/pod/IPC%3A%3AOpen2), [IPC::Open3](https://metacpan.org/pod/IPC%3A%3AOpen3) and
    [IPC::Cmd](https://metacpan.org/pod/IPC%3A%3ACmd) (not `system` and `exec`).

Own integrations are written with [Sentry::Integration::Base](https://metacpan.org/pod/Sentry%3A%3AIntegration%3A%3ABase).

# RELEASE HEALTH

With a ["release"](#release), the SDK sends
[sessions](https://develop.sentry.dev/sdk/telemetry/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"](#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"](#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](https://metacpan.org/pod/AnyEvent) loop (Twiggy) sends them once due (see
    [Sentry::Integration::AnyEvent](https://metacpan.org/pod/Sentry%3A%3AIntegration%3A%3AAnyEvent)). 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"](#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"](#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](https://metacpan.org/pod/Mojolicious%3A%3APlugin%3A%3ASentrySDK) 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"](#capture_event) at level `error`
or `fatal`; messages and log records never do. Events dropped by
["ignore\_errors"](#ignore_errors), event processors or ["before\_send"](#before_send) do not count, those
dropped by rate limits do, and so do those dropped by ["sample\_rate"](#sample_rate):
the SDK samples before running event processors and ["before\_send"](#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](https://docs.sentry.io/product/crons/) 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](https://develop.sentry.dev/sdk/telemetry/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"](#distributed-tracing)),
pass no hooks (["before\_send"](#before_send) is for errors), and are rate limited and
counted in client reports as data category `monitor`.

# LOGS

["logger"](#logger) sends [logs](https://develop.sentry.dev/sdk/telemetry/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"](#enable_logs). ["before\_send\_log"](#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"](#flush)
and ["close"](#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"](#sending)); Sentry's rate limits for
logs apply, discarded logs are counted in the client reports.

# METRICS

["metrics"](#metrics) sends
[metric values](https://develop.sentry.dev/sdk/telemetry/metrics/):
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"](#before_send_metric) filters and changes them.
They are sent in batches of up to 1000, at the same times as logs (see
["LOGS"](#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](https://metacpan.org/pod/Mojolicious%3A%3APlugin%3A%3ASentrySDK),
[CGI::Application::Plugin::Sentry](https://metacpan.org/pod/CGI%3A%3AApplication%3A%3APlugin%3A%3ASentry), [Plack::Middleware::SentrySDK](https://metacpan.org/pod/Plack%3A%3AMiddleware%3A%3ASentrySDK)).
[Sentry::SDK::Manual](https://metacpan.org/pod/Sentry%3A%3ASDK%3A%3AManual) 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"](#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](https://metacpan.org/pod/Sentry%3A%3AClient#get_options).

The options by topic:

- Basics

    ["dsn"](#dsn), ["release"](#release), ["environment"](#environment), ["dist"](#dist), ["server\_name"](#server_name),
    ["debug"](#debug), ["auto\_session\_tracking"](#auto_session_tracking)

- Errors

    ["sample\_rate"](#sample_rate), ["before\_send"](#before_send), ["ignore\_errors"](#ignore_errors), ["attach\_stacktrace"](#attach_stacktrace),
    ["include\_source\_context"](#include_source_context), ["include\_local\_variables"](#include_local_variables), ["project\_root"](#project_root),
    ["in\_app\_include, in\_app\_exclude"](#in_app_include-in_app_exclude), ["before\_breadcrumb"](#before_breadcrumb),
    ["max\_breadcrumbs"](#max_breadcrumbs), ["max\_attachment\_size"](#max_attachment_size)

- Tracing

    ["traces\_sample\_rate"](#traces_sample_rate), ["traces\_sampler"](#traces_sampler), ["before\_send\_transaction"](#before_send_transaction),
    ["ignore\_transactions"](#ignore_transactions), ["functions\_to\_trace"](#functions_to_trace), ["max\_spans"](#max_spans),
    ["enable\_db\_query\_source, db\_query\_source\_threshold\_ms"](#enable_db_query_source-db_query_source_threshold_ms),
    ["trace\_propagation\_targets"](#trace_propagation_targets), ["org\_id"](#org_id), ["strict\_trace\_continuation"](#strict_trace_continuation),
    ["enable\_backpressure\_handling"](#enable_backpressure_handling)

- Logs and metrics

    ["enable\_logs"](#enable_logs), ["before\_send\_log"](#before_send_log), ["before\_send\_metric"](#before_send_metric)

- User feedback

    ["before\_send\_feedback"](#before_send_feedback)

- Privacy

    ["send\_default\_pii"](#send_default_pii), ["denylist"](#denylist), ["event\_scrubber"](#event_scrubber),
    ["max\_request\_body\_size"](#max_request_body_size), ["record\_sql\_params"](#record_sql_params)

- Limits of event data

    ["max\_value\_length"](#max_value_length), ["normalize\_depth and normalize\_max\_breadth"](#normalize_depth-and-normalize_max_breadth)

- Integrations

    ["integrations"](#integrations), ["default\_integrations"](#default_integrations), ["disabled\_integrations"](#disabled_integrations)

- Sending

    ["transport"](#transport), ["background\_sender"](#background_sender), ["http\_timeout"](#http_timeout),
    ["shutdown\_timeout"](#shutdown_timeout), ["transport\_queue\_size"](#transport_queue_size),
    ["transport\_compression\_level"](#transport_compression_level), ["send\_client\_reports"](#send_client_reports),
    ["http\_proxy, https\_proxy"](#http_proxy-https_proxy), ["ca\_certs"](#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"](#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"](#release-health) on its own, of the
program and of each web request. Default: 1, as in sentry-python. Sessions
need a ["release"](#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"](#traces_sampler), enables tracing; unset,
no transaction is sent, but traces are still passed on (see
["DISTRIBUTED TRACING"](#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](https://metacpan.org/pod/Sentry%3A%3AIntegration%3A%3AFunctionsToTrace)).

### 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"](#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"](#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"](#sending)), or envelopes
pile up: the sender process has ["transport\_queue\_size"](#transport_queue_size) of them waiting
or its socket takes no more, or [Mojo::IOLoop](https://metacpan.org/pod/Mojo%3A%3AIOLoop) 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"](#traces_sample_rate), of ["traces\_sampler"](#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"](#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](https://metacpan.org/pod/Sentry%3A%3ATransport#is_healthy).

### 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](https://metacpan.org/pod/Sentry%3A%3ADataScrubber)): 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](https://metacpan.org/pod/Mojolicious%3A%3APlugin%3A%3ASentrySDK) 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"](#before_send), like sentry-python's option of that name: an object with
an `event` method (see ["event" in Sentry::DataScrubber](https://metacpan.org/pod/Sentry%3A%3ADataScrubber#event)), which gets the
event and returns the scrubbed copy. Defaults to a [Sentry::DataScrubber](https://metacpan.org/pod/Sentry%3A%3ADataScrubber)
with ["denylist"](#denylist), ["send\_default\_pii"](#send_default_pii) and ["max\_request\_body\_size"](#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"](#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"](#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](https://metacpan.org/pod/Mojolicious%3A%3APlugin%3A%3ASentrySDK)
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](https://metacpan.org/pod/HTTP%3A%3ATiny);
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](https://metacpan.org/pod/IO%3A%3ASocket%3A%3ASSL) uses: `SSL_CERT_FILE` or `SSL_CERT_DIR`, else those of
OpenSSL, else [Mozilla::CA](https://metacpan.org/pod/Mozilla%3A%3ACA). If that is only a directory, sending without
a running [Mojo::IOLoop](https://metacpan.org/pod/Mojo%3A%3AIOLoop) (with [HTTP::Tiny](https://metacpan.org/pod/HTTP%3A%3ATiny)) 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](https://metacpan.org/pod/HTTP%3A%3ATiny), see ["flush"](#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"](#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](https://metacpan.org/pod/Mojo%3A%3AIOLoop) 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"](#before_send), rate limits, network errors, full queues
and others; see
[client reports](https://develop.sentry.dev/sdk/telemetry/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"](#flush) and
["close"](#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"](#flush) and
["close"](#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"](#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"](#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"](#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"](#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_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"](#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"](#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"](#ignore_transactions) is simpler; to send
only some, use ["traces\_sampler"](#traces_sampler), which decides before the transaction
records anything. As with ["before\_send"](#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"](#before_send), but for feedback (["capture\_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"](#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"](#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"](#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"](#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](https://metacpan.org/pod/Mojo%3A%3ALog) or [Log::Log4perl](https://metacpan.org/pod/Log%3A%3ALog4perl) is sent as
Sentry logs as well (see ["LOGS"](#logs)), from the `logs_level` of
the logging integration on (default `info`, see
["logs\_level" in Sentry::Integration::Logging](https://metacpan.org/pod/Sentry%3A%3AIntegration%3A%3ALogging#logs_level)). Off by default: logs count
against a quota of their own, and an application may log a lot. Logs sent
with ["logger"](#logger) do not need it.

### max\_attachment\_size

Attachments ([Sentry::Attachment](https://metacpan.org/pod/Sentry%3A%3AAttachment)) 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](https://metacpan.org/pod/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"](#attach_stacktrace), and those of an exception that was
never thrown where the die handler saw it (["capture\_exception"](#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](https://metacpan.org/pod/Sentry%3A%3AIntegration%3A%3ADieHandler)), 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"](#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](https://metacpan.org/pod/DBIx%3A%3AClass%3A%3AResultSet) 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"](#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"](#integrations)), including the die handler that reports uncaught
exceptions. Custom ["integrations"](#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"](#integrations) (e.g. misspelt) is ignored with a warning.

### transport

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

The [Sentry::Transport](https://metacpan.org/pod/Sentry%3A%3ATransport) 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](https://metacpan.org/pod/Sentry%3A%3ATransport%3A%3AHttp). With a transport given, the SDK captures
events also without ["dsn"](#dsn), e.g. into [Sentry::Transport::Memory](https://metacpan.org/pod/Sentry%3A%3ATransport%3A%3AMemory); tests of
an application use [Sentry::Test](https://metacpan.org/pod/Sentry%3A%3ATest), 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"](#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](https://metacpan.org/pod/Sentry%3A%3AFeatureFlags)); 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](https://metacpan.org/pod/Sentry%3A%3ATracing%3A%3ASpan#set_flag)).

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"](#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](https://metacpan.org/pod/Devel%3A%3AStackTrace) 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](https://metacpan.org/pod/Sentry%3A%3AIntegration%3A%3ADieHandler)).

All `capture_*` functions return the id of the event, or `undef` if it
was not sent (no DSN, dropped by sampling, ["ignore\_errors"](#ignore_errors),
["before\_send"](#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](https://develop.sentry.dev/sdk/telemetry/feedbacks/) 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"](#before_send), but to
["before\_send\_feedback"](#before_send_feedback). Returns the event id, `undef` if nothing was
sent; ["last\_event\_id"](#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](https://metacpan.org/pod/Sentry%3A%3ALogs) and
["LOGS"](#logs).

## metrics

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

Sends metrics to Sentry, see [Sentry::Metrics](https://metacpan.org/pod/Sentry%3A%3AMetrics) and ["METRICS"](#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"](#with_scope) block.
See ["SCOPES"](#scopes) and [Sentry::Scope](https://metacpan.org/pod/Sentry%3A%3AScope).

## 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](https://develop.sentry.dev/sdk/data-model/event-payloads/transaction/#transaction-annotations)),
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](https://metacpan.org/pod/Sentry%3A%3AScope#set_transaction_name).

## 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"](#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"](#scopes) and [Sentry::Scope](https://metacpan.org/pod/Sentry%3A%3AScope).

## 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"](#init) puts it. Never `undef`: before ["init"](#init) and
without DSN it is a [Sentry::Client::NoOp](https://metacpan.org/pod/Sentry%3A%3AClient%3A%3ANoOp), which sends nothing. Its
options are readable with `Sentry::SDK->get_client->get_options` (see
[Sentry::Options](https://metacpan.org/pod/Sentry%3A%3AOptions)).

## 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](https://metacpan.org/pod/Sentry%3A%3ATracing%3A%3ATransaction).

A transaction without `trace_id` joins the trace the isolation scope
continues (see ["continue\_trace"](#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"](#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"](#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"](#start_transaction); further keys are
those of
["start\_child" in Sentry::Tracing::Span](https://metacpan.org/pod/Sentry%3A%3ATracing%3A%3ASpan#start_child) or ["start\_transaction"](#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"](#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"](#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"](#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](https://metacpan.org/pod/Mojo%3A%3AIOLoop). 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](https://metacpan.org/pod/Sentry%3A%3AIntegration%3A%3AMojoIOLoop)). 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"](#flush), but disables the client afterwards: nothing is captured
anymore until the next ["init"](#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"](#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](https://develop.sentry.dev/sdk/telemetry/check-ins/#monitor-upsert-support):
`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"](#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"](#release-health); ["init"](#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](https://metacpan.org/pod/Sentry%3A%3ASDK%3A%3AManual),
[Sentry's documentation](https://docs.sentry.io),
[Sentry's SDK development guide](https://develop.sentry.dev/sdk/).
