NAME

Sentry::SDK::Manual - How to set up and use Sentry::SDK

DESCRIPTION

A cookbook: how to add Sentry::SDK to each kind of Perl application, and how to capture, enrich, trace, filter and test what it sends. The reference of every function and option is Sentry::SDK; the integrations are described in their own modules (see "INTEGRATIONS" in Sentry::SDK).

The examples use subroutine signatures (use feature 'signatures', or Mojo::Base with -signatures). The DSN, release and environment are best passed in the environment variables SENTRY_DSN, SENTRY_RELEASE and SENTRY_ENVIRONMENT, which the SDK reads by itself (see "Configuration from the environment"); the examples only pass what differs.

SETUP

Call "init" in Sentry::SDK once per process, as early as possible, or let a framework plugin do it. Everything else is optional: the integrations of the modules the application loads switch on by themselves (see "INTEGRATIONS" in Sentry::SDK), exceptions nobody catches are reported, and pending events are sent when the process exits.

Scripts and cron jobs

use Sentry::SDK;

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

my $transaction = Sentry::SDK->start_transaction(
  { name => 'nightly import', op => 'task' });
Sentry::SDK->get_current_scope->set_span($transaction);

eval { run_import(); 1 } or Sentry::SDK->capture_exception($@);

$transaction->finish;

An exception that ends the script is reported, too (see Sentry::Integration::DieHandler); the exit status is the same as without the SDK. Events are sent while the script waits, at most "http_timeout" in Sentry::SDK seconds each; what is still pending at exit is sent within "shutdown_timeout" in Sentry::SDK.

Without changing the script, Sentry::SDK::Auto initializes the SDK from the environment and reports its uncaught exceptions, including compile errors such as a missing module:

# crontab
SENTRY_DSN=https://<key>@<org>.ingest.sentry.io/<project>
17 3 * * * perl -MSentry::SDK::Auto /opt/my-app/bin/import.pl

# or for every perl process of a container
export PERL5OPT=-MSentry::SDK::Auto

A script that ends with POSIX::_exit or exec skips the sending at exit: call Sentry::SDK->flush before.

A worker processing jobs runs each one in a scope of its own, so that the user, tags and breadcrumbs of one job do not end up in the events of the next:

while (my $job = $queue->next) {
  Sentry::SDK->with_isolation_scope(sub ($scope) {
    Sentry::SDK->set_tag(job_type => $job->type);
    my $transaction = Sentry::SDK->start_transaction(
      { name => $job->type, op => 'queue.process', source => 'task' });
    Sentry::SDK->get_current_scope->set_span($transaction);

    eval { $job->run; 1 } or do {
      Sentry::SDK->capture_exception($@);
      $transaction->status('internal_error');
    };
    $transaction->finish;
  });
}

Jobs enqueued by a traced request can continue its trace, see "Distributed tracing".

CGI

#!/usr/bin/perl
use CGI;
use Sentry::SDK;

Sentry::SDK->init;

my $q = CGI->new;
...

Exceptions that end the script are reported, also with use CGI::Carp qw(fatalsToBrowser), whose error page still shows. From init on, the script is one request (see Sentry::Integration::CGI): its events carry the request data, and it gets a transaction named after method and path, which ends with the HTTP status the script printed when the process exits. Initialize the SDK before the script changes %ENV. Without a DSN, init warns in a CGI request, as that is a misconfiguration there.

CGI::Application

package My::App;
use parent 'CGI::Application';

use CGI::Application::Plugin::Sentry;

That is all: the plugin initializes the SDK at the first request from the SENTRY_* environment variables. Every request gets a transaction named after the class and run mode (My::App#show) and its exceptions are reported. Options go into the application parameter sentry_options:

sub cgiapp_init ($self) {
  $self->param(sentry_options => {
    traces_sample_rate => 0.2,
    before_send        => sub ($event, $hint) {
      my $c = $hint->{cgiapp} or return $event;
      $event->{tags}{customer} = $c->param('customer');
      return $event;
    },
  });
}

Under CGI, the events are sent once the response has been printed. Set the user and other request data in cgiapp_prerun or later, not in cgiapp_init: see "Requests" in CGI::Application::Plugin::Sentry.

Applications are instrumented without the plugin as well, once init has run in the process, e.g. in the startup file of mod_perl or before a FastCGI loop (see Sentry::Integration::CGIApplication).

FastCGI

use CGI::Fast;
use Sentry::SDK;

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

while (my $q = CGI::Fast->new) {
  ...
}

Initialize before the loop. Every request gets its own scopes and a transaction; CGI::Application applications in the loop adopt it. Events are handed to a sender process, so the next request does not wait for Sentry (see "SENDING"). With a process manager such as FCGI::ProcManager, initialize in the manager, before it forks. Details: Sentry::Integration::FCGI.

FCGI ties STDIN to the request, so it has no file descriptor a child process could inherit. IPC::Cmd's run dies on it, after warning Could not dup 'STDIN', with or without the SDK. Give the child another STDIN:

local *STDIN;
open STDIN, '<', '/dev/null' or die "/dev/null: $!\n";
my ($ok, $error) = IPC::Cmd::run(command => ['gzip', '-k', $file]);

mod_perl

# httpd.conf
PerlPassEnv SENTRY_DSN
PerlPassEnv SENTRY_RELEASE
PerlPassEnv SENTRY_ENVIRONMENT
PerlPostConfigRequire /etc/apache2/startup.pl

# startup.pl
use Sentry::SDK;
Sentry::SDK->init({ traces_sample_rate => 0.2 });
1;

mod_perl hides the environment of the server from Perl: pass the SENTRY_* variables with PerlPassEnv or PerlSetEnv. Initialized in the startup file, every request of the server gets its own scopes and a transaction, whatever handles it:

ModPerl::Registry and ModPerl::PerlRun scripts
<Location /cgi-bin>
  SetHandler perl-script
  PerlResponseHandler ModPerl::Registry
  Options +ExecCGI
</Location>

No change to the scripts. Their frames are named after the script, so each script groups its errors on its own.

Response handlers
<Location /hello>
  SetHandler perl-script
  PerlResponseHandler My::Handler
</Location>

A handler that dies is reported with its message; status 500 and the transaction's internal_error follow.

CGI::Application applications

They adopt the request and name its transaction after their run mode.

Events are sent in the cleanup phase, after the response; the worker serves no other request meanwhile. Virtual hosts with an interpreter of their own (PerlOptions +Parent) and the prefork MPM requirement are described in "Setup" in Sentry::Integration::ModPerl.

Plack and Starman

# app.psgi
use Plack::Builder;

builder {
  enable 'SentrySDK', traces_sample_rate => 0.2;
  $app;
};

# starman --workers 10 app.psgi

The middleware initializes the SDK with the options given to enable (without options, call init yourself before). Every request gets its own scopes and a transaction named after method and path; Mojolicious and CGI::Application applications inside adopt it. Under servers with persistent workers (Starman, Starlet...) each worker hands its events to a sender process of its own (see "SENDING"). Details: Plack::Middleware::SentrySDK.

Mojolicious

# Mojolicious::Lite
plugin SentrySDK => { traces_sample_rate => 0.2 };

# Full app
sub startup ($self) {
  $self->plugin(SentrySDK => $self->config->{sentry} // {});
  ...
}

Register the plugin first, before plugins that add hooks or a reply.exception helper. It initializes the SDK at once, so commands and job queue workers of the application report as well; pass dsn => '' or a Sentry::Transport::Memory in a test configuration, as SENTRY_DSN would be read otherwise. Every request gets a transaction named after method and route (GET /users/:id); callbacks of promises, timers and non-blocking requests keep the scopes of their request (see Sentry::Integration::MojoIOLoop). Details: Mojolicious::Plugin::SentrySDK.

In a Mojolicious::Lite application, plugin SentrySDK loads the SDK only when the file runs, after perl has compiled the whole file: backticks and qx// in its routes then get no span (see "Backticks and qx//" in Sentry::Integration::Subprocess). Load the SDK before them:

use Mojolicious::Lite -signatures;
use Sentry::SDK;    # before the code running commands

plugin SentrySDK => { traces_sample_rate => 0.2 };

get '/kernel' => sub ($c) { $c->render(text => `uname -s`) };

or start the application with perl -MSentry::SDK app.pl daemon.

daemon

./app.pl daemon (or morbo) sends in the background of the event loop.

prefork, hypnotoad

The manager initializes the SDK, each worker sends on connections of its own. A worker stopped gracefully sends what is pending before it exits; one killed with INT or TERM loses it. Under systemd, stop gracefully with KillSignal=SIGQUIT and a TimeoutStopSec above the server's graceful_timeout (default 120 seconds):

[Service]
Type=forking
PIDFile=/opt/my-app/script/hypnotoad.pid
ExecStart=/usr/bin/hypnotoad /opt/my-app/script/my_app
ExecReload=/usr/bin/hypnotoad /opt/my-app/script/my_app
KillMode=process
KillSignal=SIGQUIT
TimeoutStopSec=130

See "Deployment" in Mojolicious::Plugin::SentrySDK.

behind a reverse proxy

The SDK does not read X-Forwarded-* headers itself: the URL and client address of a request are what Mojolicious makes of it. Unless Mojolicious is told that it runs behind a proxy, request URLs are http:// (the proxy talks plain HTTP to it) and the client address (sent with "send_default_pii" in Sentry::SDK) is the proxy's. Tell it with ./app.pl daemon -p or ./app.pl prefork -p (-p 10.0.0.0/8 trusts only proxies of that network), proxy => 1 or trusted_proxies => [...] in the hypnotoad configuration, or the environment variables MOJO_REVERSE_PROXY=1 or MOJO_TRUSTED_PROXIES=10.0.0.0/8. Trusting all proxies (-p, MOJO_REVERSE_PROXY) is only safe if clients cannot reach the application directly, as they could set X-Forwarded-For themselves.

Mojolicious under a PSGI server

Run with plackup or Starman, the application gets its requests from the server: wrap it in Plack::Middleware::SentrySDK or keep the plugin alone; events go to a sender process either way.

Configuration from the environment

Options not passed to init are read from these environment variables:

SENTRY_DSN                 dsn
SENTRY_RELEASE             release
SENTRY_ENVIRONMENT         environment
SENTRY_TRACES_SAMPLE_RATE  traces_sample_rate
SENTRY_MAX_BREADCRUMBS     max_breadcrumbs
SENTRY_SEND_DEFAULT_PII    send_default_pii (true/false, yes/no, on/off, 1/0)
SENTRY_DEBUG               debug output (see TROUBLESHOOTING)
SENTRY_TRACE, SENTRY_BAGGAGE  continue a trace (see Distributed tracing)

An empty variable counts as unset. Under FastCGI, variables the web server passes with a request take precedence over those of the process. Options passed to init take precedence over all of them; an empty dsn turns the SDK off.

CAPTURING

# An exception, with the stack trace of the place it was thrown
eval { charge($order); 1 } or Sentry::SDK->capture_exception($@);

# A message, level info unless given
Sentry::SDK->capture_message('Payment provider slow', 'warning');

# Data for this event only
Sentry::SDK->capture_exception($@, {
  tags        => { provider => 'acme' },
  extra       => { order_id => $order->id },
  fingerprint => ['payment-failed', '{{ default }}'],
});

# The id, e.g. for an error page
my $event_id = Sentry::SDK->last_event_id;

Exceptions of every kind are reported: strings (with the stack trace recorded where they were thrown), Exception::Class, Throwable, Mojo::Exception and other objects (with their own stack trace if they carry a Devel::StackTrace), and unblessed references. Causes reachable via cause, previous or previous_exception are sent as chained exceptions. The capture_* functions never die and return the event id, or undef if nothing was sent.

Uncaught exceptions are reported by Sentry::Integration::DieHandler, exceptions of requests by the web integrations. Errors the application only logs become breadcrumbs (see Sentry::Integration::Logging); set event_level there to send logged errors as events, too.

Local variables

With PadWalker, a dependency of the SDK, the frames of exceptions carry the values of the lexical variables in scope where the exception was thrown, as in sentry-python:

sub charge ($order, $amount) {
  my $provider = $order->provider;
  die "charge failed\n" if $amount <= 0;    # frame vars: $order, $amount, $provider
}

Sentry shows them under each frame of the stack trace. Up to 5 frames per exception carry them, application code first, with small, cut values (see "include_local_variables" in Sentry::SDK). Variables named like credentials ($password, $api_token, keys like Authorization) are sent as [Filtered], and further names can be added with "denylist" in Sentry::SDK; other values, e.g. of $email, are sent as they are, also without "send_default_pii" in Sentry::SDK. Turn them off with:

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

SCOPES

Data set with the top-level functions goes into the isolation scope of the current request or job and is attached to every event captured in it:

Sentry::SDK->set_user({ id => $user->id });
Sentry::SDK->set_tag(tenant => $tenant->name);
Sentry::SDK->set_context(order => { id => $order->id, total => $total });
Sentry::SDK->add_breadcrumb({ category => 'cart', message => 'item added' });

The web integrations give every request its own scopes, so this data never leaks into the next request. For data that applies to one block only, use "with_scope" in Sentry::SDK:

Sentry::SDK->with_scope(sub ($scope) {
  $scope->set_tag(batch => $batch->id);
  $scope->set_level('warning');
  Sentry::SDK->capture_message('batch incomplete');
});

Data for all events of the process goes into the global scope:

Sentry::SDK->get_global_scope->set_tag(datacenter => 'fra1');

Callbacks of non-blocking code run after the block that registered them. Under Mojolicious they keep their scopes automatically; elsewhere wrap them with "bind_scopes" in Sentry::Scope. See "SCOPES" in Sentry::SDK.

ATTACHMENTS

Files that explain an error, such as the input of a failed job or a log excerpt, go with the errors and messages captured in a scope:

Sentry::SDK->with_scope(sub ($scope) {
  $scope->add_attachment({ path => $job->input_file });
  $scope->add_attachment({
    bytes    => encode_json($payload),
    filename => 'payload.json',
  });
  process($job, $payload);    # errors captured here carry both files
});

# For every event of the request or job
Sentry::SDK->get_isolation_scope->add_attachment(
  { path => '/var/log/myapp/import.log' });

Files are read only when an event is sent, so attaching costs nothing until something fails; transactions carry none. Larger than "max_attachment_size" in Sentry::SDK (20 MiB) or unreadable, a file is left out with a warning. See Sentry::Attachment.

USER FEEDBACK

A feedback form can send what users report, linked to the error they saw:

# On the error page: the id of the error, e.g. in a hidden field
my $event_id = Sentry::SDK->last_event_id;

# In the handler of the form
Sentry::SDK->capture_feedback({
  message             => $form->{message},
  name                => $form->{name},
  email               => $form->{email},
  associated_event_id => $form->{event_id},
});

Sentry shows it under User Feedback and with the error. Feedback is never sampled and does not pass before_send; filter or change it with "before_send_feedback" in Sentry::SDK. See "capture_feedback" in Sentry::SDK.

FEATURE FLAGS

Errors can show which feature flags were on when they happened: record each evaluation where the application decides on a flag, e.g. in a wrapper around the flag service's client:

sub feature_enabled ($self, $name) {
  my $enabled = $self->flag_client->is_enabled($name, $self->user);
  Sentry::SDK->add_feature_flag($name => $enabled);
  return $enabled;
}

The request or job keeps the 100 flags evaluated last; its errors carry them, shown in Sentry's Feature Flags section of the issue. The active span records the first 10 flags evaluated in it as span data flag.evaluation.<name>, so traces can be searched by flag. Sentry knows boolean flags only: results are taken by Perl's truth. See "add_feature_flag" in Sentry::SDK.

TRACING

Tracing is enabled by "traces_sample_rate" in Sentry::SDK or "traces_sampler" in Sentry::SDK. The web integrations then record a transaction per request, and the integrations of databases, caches, HTTP clients and templates add spans to it.

Transactions and spans of your own

my $transaction = Sentry::SDK->start_transaction(
  { name => 'rebuild search index', op => 'task' });
Sentry::SDK->get_current_scope->set_span($transaction);

for my $shard (@shards) {
  my $span = $transaction->start_child(
    { op => 'index.shard', description => "shard $shard" });
  rebuild($shard);
  $span->finish;
}

$transaction->finish;

Within a request, add spans to the request's transaction with "start_span" in Sentry::SDK, which starts a child of the active span (or a transaction if none is active):

my $span = Sentry::SDK->start_span({ op => 'pdf.render', name => 'invoice' });
my $pdf  = render_invoice($order);
$span->set_data('pdf.pages' => $pdf->pages);
$span->finish;

A span is not the active one by starting it; to nest spans in it, make it active in a block of its own:

Sentry::SDK->with_scope(sub ($scope) {
  $scope->set_span($span);
  ...;    # spans of the integrations are children of $span
});

Spans not finished when their transaction finishes are not sent. See Sentry::Tracing::Transaction and Sentry::Tracing::Span.

Tracing functions without changing them

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

Every call of these functions while a span is active gets a span, which is the active one during the call. Call init before the code takes references to them. See "functions_to_trace" in Sentry::SDK.

Sampling

"traces_sample_rate" in Sentry::SDK sends the same share of all transactions. "traces_sampler" in Sentry::SDK decides per transaction:

Sentry::SDK->init({
  traces_sampler => sub ($context) {
    return $context->{parent_sampled} if defined $context->{parent_sampled};

    my $name = $context->{transaction_context}{name} // '';
    return 0 if $name =~ m{/health\z};
    return 1 if $name =~ /\A(?:POST|PUT) /;
    return 0.1;
  },
});

Returning $context->{parent_sampled} first keeps the decision of a calling service, so that traces stay complete. Errors are sampled separately with "sample_rate" in Sentry::SDK.

Distributed tracing

Services using a Sentry SDK continue each other's traces through the sentry-trace and baggage headers, without configuration: the web integrations read them from incoming requests, and the HTTP::Tiny, LWP::UserAgent, Mojo::UserAgent and AnyEvent::HTTP integrations add them to outgoing requests.

By default the headers go to every host the application calls, as in sentry-python, also to third-party APIs. They carry ids and sampling values, no user data; to keep them to your own services, list them:

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

See "trace_propagation_targets" in Sentry::SDK.

Work that does not travel by HTTP passes the trace on by hand. The producer sends the header values along:

$queue->enqueue({
  payload      => $payload,
  sentry_trace => Sentry::SDK->get_traceparent,
  baggage      => Sentry::SDK->get_baggage,
});

and the consumer continues the trace in a scope of its own:

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

A process started by a traced one continues its trace from the environment variables SENTRY_TRACE and SENTRY_BAGGAGE. Commands run with backticks, IPC::Open3 or IPC::Cmd get them by themselves (see "Commands"); for system, set them:

local $ENV{SENTRY_TRACE}   = Sentry::SDK->get_traceparent;
local $ENV{SENTRY_BAGGAGE} = Sentry::SDK->get_baggage;
system 'perl', 'bin/export.pl';

For a browser SDK on the page, render the values as <meta name="sentry-trace"> and <meta name="baggage"> tags. See "DISTRIBUTED TRACING" in Sentry::SDK.

LOGS

Sentry's logs are searchable by their attributes and linked to the trace and span they were written in:

my $log = Sentry::SDK->logger;
$log->info('Order %s placed', [$order->id], { 'order.items' => 3 });
$log->warn('Payment provider slow', { provider => 'acme' });

To send what the application already logs with Mojo::Log or Log::Log4perl, turn on "enable_logs" in Sentry::SDK; the logging integrations then send messages from info on (their logs_level). Logs are sent in batches, at the latest when a request ends and when the process exits. See "LOGS" in Sentry::SDK.

METRICS

Counters, gauges and distributions, linked to the trace and span they were taken in:

my $metrics = Sentry::SDK->metrics;
$metrics->count('order.placed');
$metrics->gauge('queue.length', $queue->size);
$metrics->distribution('order.value', $total,
  { unit => 'euro', attributes => { country => $order->country } });

Sentry aggregates the values; keep attribute values to a small set (no ids). They are sent in batches like logs. See "METRICS" in Sentry::SDK.

INTEGRATIONS

The integrations of the modules an application uses switch on by themselves once the module is loaded, before or after init; they never load a module themselves. Nothing has to be configured: the examples below are plain application code, and what the comments name is what Sentry gets. Spans are recorded within a transaction (of a request, or your own), breadcrumbs are attached to the errors that follow. The full list is in "INTEGRATIONS" in Sentry::SDK; each integration's module describes the details.

Turn one off, or configure it, in init:

Sentry::SDK->init({
  disabled_integrations => ['Sentry::Integration::Subprocess'],

  # breadcrumbs => 0: spans only; tracing => 0: breadcrumbs only
  integrations => [Sentry::Integration::DBI->new(breadcrumbs => 0)],
});

The integrations record what was done, not the data it was done with: no mail, template or document content, no request or response bodies, and not the passwords of connecting or logging in (DBI, LDAP, FTP, SMTP). Without "send_default_pii" in Sentry::SDK, ids and tokens in keys and paths become * and values in MongoDB commands and LDAP filters placeholders; with it, MongoDB commands are sent with all their values. User info is removed from URLs; sensitive query parameters and options of command lines named like credentials are always [Filtered]. SQL statements are sent as the application wrote them, so keep values in bind parameters, which are only recorded with "record_sql_params" in Sentry::SDK.

Databases

my $dbh = DBI->connect('dbi:Pg:dbname=shop;host=db;port=5432', $user, $password);
# span "connect" (op db), with db.system.name, db.driver.name,
# db.namespace, server.address, server.port and db.user, never the
# password

my $rows = $dbh->selectall_arrayref(
  'SELECT * FROM orders WHERE customer = ?', undef, $id);
# span (op db) with the statement, db.response.returned_rows;
# breadcrumb (category query); bind values only with record_sql_params

$dbh->do(q{SELECT GET_LOCK('import', 10)});
# op db.lock: waiting for a lock stands out from slow queries

Sentry::Integration::DBI records statements of do, execute and the select* methods, and connections. Rows fetched after execute count to the statement's span, with the time spent fetching them as db.fetch.duration_ms, as many drivers read rows only when they are fetched; fetches of statements without span run DBI's code alone. Queries slower than "enable_db_query_source, db_query_source_threshold_ms" in Sentry::SDK (100 ms) name the line of application code that ran them, which Sentry's Queries insight shows. With DBIx::Class, the spans name the result source and its table (Sentry::Integration::DBIxClass).

$dbh->begin_work;          # span BEGIN (op db)
$dbh->do(...);
$dbh->commit;              # span COMMIT: how long syncing and locks took

$schema->txn_do(\&My::App::Orders::import, $schema, $file);
# span My::App::Orders::import (op db.sql.transaction), around BEGIN,
# the statements, savepoints of nested transactions, COMMIT or ROLLBACK

Transactions show where they begin and end and whether they were rolled back: begin_work, commit, rollback and turning AutoCommit off and on are spans BEGIN, COMMIT and ROLLBACK ("Transactions" in Sentry::Integration::DBI); txn_do of DBIx::Class is a span around its transaction, with the status internal_error if its code dies, which stays the application's exception.

my $users = $mongo->get_database('shop')->get_collection('users');
$users->find({ email => $email })->all;
# span (op db): {"find":"users","filter":{"email":"%s"},...}

The official MongoDB driver (Sentry::Integration::MongoDB): commands as JSON, their values replaced by %s without send_default_pii, as in sentry-python.

$es->search(index => 'articles', body => { query => {...} });
# span (op db): "GET /articles/_search", never the query

Search::Elasticsearch (Sentry::Integration::Elasticsearch): method and path, with document ids as * without send_default_pii.

$ldap->search(base => 'ou=people,dc=example,dc=com', scope => 'one',
  filter => "(uid=$uid)");
# span (op db.ldap): "search ou=people,dc=example,dc=com scope=one (uid=?)"

Net::LDAP (Sentry::Integration::NetLDAP): operations with their DN and filter. Without send_default_pii, filter values become ? and the values of RDNs naming an entry *; passwords and attribute values are never recorded.

Redis and Redis::Fast (Sentry::Integration::Redis) and Cache::Memcached (Sentry::Integration::CacheMemcached) record commands with their keys, never the values.

HTTP and remote services

my $response = HTTP::Tiny->new->get('https://api.example.com/users/42');
# span (op http.client): "GET https://api.example.com/users/42";
# breadcrumb (category http); sentry-trace and baggage headers

HTTP::Tiny (Sentry::Integration::HttpTiny), LWP::UserAgent (Sentry::Integration::LwpUserAgent), Mojo::UserAgent (Sentry::Integration::MojoUserAgent) and AnyEvent::HTTP (Sentry::Integration::AnyEventHTTP) record requests and pass the trace on (see "Distributed tracing"). Requests of the SDK itself to Sentry are not recorded.

my $soap = SOAP::Lite->proxy('https://soap.example.com/quotes');
$soap->call('getQuote', $symbol);
# span (op rpc): "getQuote", with rpc.method and the endpoint;
# the HTTP request is its child span

SOAP::Lite (Sentry::Integration::SoapLite): neither parameters nor results.

my $graphql = GraphQL::Client->new(url => 'https://api.example.com/graphql');
my $result  = $graphql->execute('query GetUser($id: ID!) { user(id: $id) { name } }',
  { id => 42 });
# span (op http.client): "POST https://api.example.com/graphql (query GetUser)",
# with graphql.operation.type and graphql.operation.name;
die encode_json($result->{errors}) if $result->{errors};
# the event of the die has the GraphQL request as request

GraphQL::Client (Sentry::Integration::GraphQLClient), like sentry-python's gql integration: the HTTP client integration records the request, this one adds the operation. Errors of the response create no event of their own, but a breadcrumb; the events captured afterwards in the unit of work (e.g. the request served) get the GraphQL request. The document, the variables and the errors only with "send_default_pii" in Sentry::SDK.

$s3->bucket('photos')->add_key_filename("users/$id/avatar.png", $file);
# span (op http.client): "S3 PutObject", with aws.s3.bucket and
# aws.s3.key "users/*/avatar.png" without send_default_pii

Net::Amazon::S3 and Net::Amazon::S3::Client (Sentry::Integration::NetAmazonS3), named after the S3 operation like sentry-python's boto3 integration.

$apns->prepare($device_token, { aps => { alert => 'Shipped' } }, sub {...})
  ->notify;
# span (op http.client) with the HTTP status and, if rejected,
# apns.reason; the device token only with send_default_pii

Net::APNS::Simple (Sentry::Integration::NetApnsSimple): push notifications, never their payload.

Mail and file transfer

MIME::Lite->new(From => $from, To => $to, Subject => 'Invoice', Data => $text)
  ->send('smtp', 'mail.example.com');
# span (op mail.send): "smtp", with the SMTP commands as child spans
# (op smtp.client); breadcrumb (category mail)

MIME::Lite (Sentry::Integration::MIMELite) and Net::SMTP (Sentry::Integration::NetSMTP): never the message, its subject or credentials; sender and recipients only with send_default_pii.

my $ftp = Net::FTP->new('ftp.example.com');
$ftp->login($user, $password);
$ftp->put($file, "/exports/$id/report.csv");
# spans (op ftp.client): "login", "put /exports/*/report.csv"

Net::FTP (Sentry::Integration::NetFTP): commands with the remote path, never the user name or password.

Templates, XSLT, images and archives

my $template = HTML::Template->new(filename => 'invoice.tmpl');
$template->param(items => \@items);
print $template->output;
# spans "invoice.tmpl": template.parse (new), template.render (output)

HTML::Template (also through CGI::Application's load_tmpl, Sentry::Integration::HTMLTemplate), HTML::Template::Pro (Sentry::Integration::HTMLTemplatePro), XML::LibXSLT (Sentry::Integration::LibXSLT, stylesheets as templates), Template (Sentry::Integration::TemplateToolkit) and Mojo::Template (Sentry::Integration::MojoTemplate): spans named after the template file, never its content or parameters.

my $image = Image::Magick->new;
$image->Read($upload);       # span image.read
$image->Resize('800x600');   # span image.process "Resize"
$image->Write($thumbnail);   # span image.write

Image::Magick and Graphics::Magick, subclasses included (Sentry::Integration::ImageMagick): reading, writing and the expensive operations; a call returning an error gets the status internal_error.

my $zip = Archive::Zip->new;
$zip->addTree('export/');
$zip->writeToFileNamed('export.zip');
# spans file.zip.add and file.zip.write "export.zip", with file.size
# and file.zip.member_count; the path only with send_default_pii

Archive::Zip (Sentry::Integration::ArchiveZip): reading, writing, extracting and adding whole trees.

Commands

my $version = `git describe --tags`;
# span (op subprocess): "git describe --tags", with process.exit.code;
# breadcrumb (category subprocess)

my ($ok, $error) = IPC::Cmd::run(command => ['convert', $in, $out]);

Sentry::Integration::Subprocess records backticks, qx//, IPC::Open2, IPC::Open3 and IPC::Cmd's run, not system, exec or piped opens. The started process gets the trace in SENTRY_TRACE and SENTRY_BAGGAGE, so a Perl program using this SDK or a Python one using sentry-python continues it. Values of options and variables named like credentials (--password=..., API_KEY=...) are [Filtered]; keep other secrets out of command lines.

Backticks are recorded through an override of readpipe that the SDK installs when it is loaded, and perl only applies it to code compiled afterwards: load Sentry::SDK before the code running commands (see "Mojolicious" for Mojolicious::Lite).

Event loops

Callbacks of Mojo::IOLoop, Mojo::Promise (Sentry::Integration::MojoIOLoop) and AnyEvent watchers, condition variables and handles (Sentry::Integration::AnyEvent, any backend) run in the scopes they were registered in: the user, tags and the span of a request reach the events and spans of its callbacks.

my $cv = AE::cv;
Sentry::SDK->with_isolation_scope(sub ($scope) {
  Sentry::SDK->set_user({ id => $job->user_id });
  my $w; $w = AE::timer 1, 0, sub {
    undef $w;
    eval { $job->finish; 1 } or Sentry::SDK->capture_exception($@);    # has the user
    $cv->send;
  };
});
$cv->recv;

Other callbacks can be bound with "bind_scopes" in Sentry::Scope.

Logging

Log messages of Mojo::Log and Log::Log4perl become breadcrumbs; with event_level, logged errors become events, too, and with "enable_logs" in Sentry::SDK messages become Sentry logs (see "LOGS" and Sentry::Integration::Logging).

RELEASE HEALTH

With a release (SENTRY_RELEASE or "release" in Sentry::SDK), the SDK sends sessions, from which Sentry shows how many runs or requests of a release had errors or crashed, and its crash-free rate:

SENTRY_RELEASE=my-app@1.4.2 perl bin/import.pl
web applications

Each request is a session: errored by a captured error, crashed if it died. They are counted per minute and sent as aggregates, through the sender process where there is one.

scripts, cron jobs, workers

The run of the program is one session, from init to exit: exited, or crashed after an uncaught exception. Commands of a Mojolicious application with the plugin (routes, job workers, hypnotoad deploys) send none: its health is that of its requests. A long running worker whose work comes in phases can end it and start a new one:

Sentry::SDK->end_session;      # before waiting for the next batch
wait_for_work();
Sentry::SDK->start_session;

Sessions need no other configuration, and are not sent without a release. Turn them off with auto_session_tracking => 0. See "RELEASE HEALTH" in Sentry::SDK for what counts as an error.

CRON MONITORING

A cron job tells Sentry when it starts and how it ended, so that Sentry alerts when it did not run, failed or ran too long:

# bin/report.pl, run by cron at 2:00
use Sentry::SDK;
Sentry::SDK->init;

Sentry::SDK->monitor(
  'nightly-report',
  sub { build_report() },
  {
    schedule       => { type => 'crontab', value => '0 2 * * *' },
    checkin_margin => 10,    # minutes late before it counts as missed
    max_runtime    => 60,    # minutes
    timezone       => 'Europe/Berlin',
  }
);

monitor checks in in_progress, runs the code and checks in ok, or error if the code died (and rethrows that). With the configuration, Sentry creates the monitor of the slug, or updates it; without, it has to exist. Where the job is not one block of code, check in by hand:

my $check_in_id = Sentry::SDK->capture_check_in(
  { monitor_slug => 'nightly-report', status => 'in_progress' });
...;
Sentry::SDK->capture_check_in({
  monitor_slug => 'nightly-report',
  check_in_id  => $check_in_id,
  status       => $failed ? 'error' : 'ok',
  duration     => $seconds,
});

See "capture_check_in" in Sentry::SDK for the configuration keys.

FILTERING

Sentry::SDK->init({
  # Exceptions to drop: class names (and subclasses) or message patterns
  ignore_errors => ['My::Exception::NotFound', qr/^Client closed connection/],

  # Transactions to drop by name; strings match the end of the name
  ignore_transactions => ['/health', qr{^GET /static/}],

  # The last word on errors and messages
  before_send => sub ($event, $hint) {
    return undef if ($hint->{original_exception} // '') =~ /^Timeout/;
    $event->{tags}{shard} = $ENV{SHARD};
    return $event;
  },

  # The last word on transactions
  before_send_transaction => sub ($transaction, $hint) {
    return undef if $transaction->{transaction} =~ m{\AGET /metrics};
    return $transaction;
  },

  # Breadcrumbs, before they are added
  before_breadcrumb => sub ($breadcrumb, $hint) {
    return undef if ($breadcrumb->{category} // '') eq 'redis';
    return $breadcrumb;
  },
});

Order: "sample_rate" in Sentry::SDK and "ignore_errors" in Sentry::SDK (errors) or "ignore_transactions" in Sentry::SDK (transactions), then the event processors and the scrubbing, then before_send or before_send_transaction. Whatever is dropped is counted in Sentry's statistics (see "send_client_reports" in Sentry::SDK). A callback that dies drops the event and logs the error.

Single integrations are turned off with "disabled_integrations" in Sentry::SDK, or configured by passing an instance:

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

PRIVACY

By default, events carry no personal data the SDK collects itself: request data leaves out cookies, client IP addresses and the headers of authenticating proxies; credentials (passwords, tokens, session ids, authorization headers...) are always replaced by [Filtered], also in the data the application sets (extra, user, breadcrumbs, spans); the ids and tokens in cache and Redis keys become *. What the application puts into events, e.g. with set_user, is sent as it is, apart from that filtering, and so are the values of variables in stack traces (see "Local variables").

send_default_pii
Sentry::SDK->init({ send_default_pii => 1 });    # or SENTRY_SEND_DEFAULT_PII=1

Sends cookies, client IP addresses and proxy user headers, and the keys of cache spans unmasked. Credentials stay filtered.

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

Further names of parameters, headers, cookies and keys to filter.

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

Turns off the scrubbing of the data the application sets, e.g. where extra holds a key named like a credential that is none. Request data is scrubbed anyway. An own Sentry::DataScrubber (or any object with an event method) replaces the scrubber.

max_request_body_size
Sentry::SDK->init({ max_request_body_size => 'never' });

How much of a request body (form parameters, JSON) to send: never, small (1000 bytes), medium (10000 bytes, default) or always.

record_sql_params

Bind values of SQL statements are only recorded with this option.

include_source_context

Set to 0 to send no source code lines with stack traces.

include_local_variables

Set to 0 to send no values of variables with stack traces (see "Local variables").

To see exactly what leaves the process, capture into Sentry::Transport::Memory (see "TESTING") or enable "TROUBLESHOOTING" output. See Sentry::DataScrubber for the list of filtered names.

APPLICATION CODE IN STACK TRACES

Sentry shows frames of application code (in_app) expanded and groups issues by them. A frame counts as application code if its file lies below "project_root" in Sentry::SDK (default: the working directory at init; in Mojolicious applications their home) and not in a library directory (perl's own, CPAN's, local::lib, Carton's local/lib/perl5).

If the application's modules live outside the working directory, e.g. a daemon started from / or modules installed into a library directory, their frames count as library code and issues are grouped by frames of CPAN modules. Name them instead:

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

in_app_include is the more robust choice: it does not depend on where the application is started or installed. Alternatively set project_root to the application's directory.

SENDING

How events travel depends on the kind of process; the defaults are meant to keep both the response and the worker from waiting for Sentry:

Scripts, cron jobs, CGI, Windows

Sent with HTTP::Tiny while the process waits, at most "http_timeout" in Sentry::SDK seconds (default 2) each. After repeated network errors, events are dropped for a while instead of slowing down every request.

CGI::Application under CGI, Plack without sender process

Held back during the request and sent once the response is complete.

FastCGI loops, PSGI servers (Starman etc.), Mojolicious or CGI::Application as PSGI application

Handed to a sender process: a small perl process each worker starts on its first event, which costs about 20 to 30 MB resident per worker (partly shared libraries).

mod_perl

Sent in the cleanup phase after the response, as a sender process per Apache child would cost too much memory. background_sender => 1 uses it anyway.

Mojolicious daemons (daemon, prefork, hypnotoad)

Sent in the background of the event loop.

"background_sender" in Sentry::SDK overrides the choice (background_sender => 0: never a sender process). At most "transport_queue_size" in Sentry::SDK events (default 100) wait; further ones are dropped and counted.

Pending events are sent at a normal exit within "shutdown_timeout" in Sentry::SDK (default 2 seconds). To make sure they are out earlier, e.g. before a long sleep or exec:

my $all_sent = Sentry::SDK->flush(5);    # wait at most 5 seconds
Sentry::SDK->close;                      # flush, then capture nothing more

The sender process ignores TERM and ends on its own once its worker has ended, at most shutdown_timeout seconds later. Under systemd with the default KillMode=control-group, a stop or restart of the service may therefore take that long if Sentry is slow or unreachable, but no event the sender got is cut off. See "SENDING" in Sentry::SDK for the details, and the options "http_proxy, https_proxy" in Sentry::SDK and "ca_certs" in Sentry::SDK for the way to Sentry.

TESTING

To check what your application reports, start Sentry::Test in the test. It captures however and whenever the application initializes the SDK: before or after start, through the Mojolicious plugin, the Plack middleware or the CGI::Application plugin, in a server hook, even without DSN. Nothing is sent and nothing runs in the background.

use Test::More;
use Sentry::Test;

my $sentry = Sentry::Test->start({ traces_sample_rate => 1 });

My::App->new->run_failing_job;

is $sentry->last_event->{exception}{values}[-1]{type},
  'My::Exception::Timeout';
is scalar $sentry->transactions->@*, 1;
is_deeply $sentry->discarded_events, [];

$sentry->clear;    # before the next case

events holds errors and messages, transactions the transactions; logs, metrics, feedback and attachments($event) show the rest. Forked workers are not captured, so test in the test's process (Test::Mojo and Plack::Test do by default).

Test helpers

Keep tests independent of each other: clear the capture between cases and run code that sets scope data inside "with_isolation_scope" in Sentry::SDK, so that tags or users of one test do not reach the events of the next; Sentry::Test does not reset scopes. Don't mock Sentry::SDK's functions: Sentry::Test sees the events as they would be sent, after sampling, scrubbing and before_send.

TROUBLESHOOTING

Nothing arrives in Sentry

Run with debug output, which goes to STDERR:

SENTRY_DEBUG=1 perl script.pl

or debug => 1 in the options. It shows every envelope sent (ids and sizes, not the data), the sampling decisions of transactions and why events were dropped. SENTRY_DEBUG also takes a comma separated list of contexts with * as wildcard, e.g. SENTRY_DEBUG=Tracing,Sentry::Transport::*.

Common causes: no DSN (init says so in CGI and FastCGI requests and under mod_perl; under mod_perl the variables need PerlPassEnv), a proxy or firewall blocking the envelope endpoint (/api/<project>/envelope/), an unknown certificate authority of a self-hosted Sentry ("ca_certs" in Sentry::SDK), rate limits of the project, or before_send returning nothing.

Warnings on STDERR

Warnings and errors of the SDK (an invalid option, Sentry unreachable, an integration that does not fit its module's version) are printed to STDERR also without debug output, the same message at most once a minute. The SDK never dies because of them.

Fewer transactions than sampled

While Sentry rate-limits the project, cannot be reached or does not keep up, the SDK samples fewer transactions on its own ("enable_backpressure_handling" in Sentry::SDK). Debug output then says Health check negative, and Sentry's statistics count them as backpressure.

Errors grouped wrongly

See "APPLICATION CODE IN STACK TRACES". Messages with variable parts (ids, names) make an issue each: put the variable parts into tags or extra, or set a fingerprint.

No spans for backticks

Backticks and qx// compiled before Sentry::SDK was loaded are not recorded, e.g. in a Mojolicious::Lite file that loads the SDK with plugin SentrySDK. Load it first (see "Mojolicious").

Inspecting the options
my $options = Sentry::SDK->get_client->get_options;
print $options->{release}, "\n";

SEE ALSO

Sentry::SDK, Sentry::Scope, Sentry::Tracing::Transaction, Sentry::DataScrubber, Sentry's documentation.