| 1 | package Mojolicious::Plugin::SentrySDK; | ||
| 2 | use Mojo::Base 'Mojolicious::Plugin', -signatures; | ||
| 3 | |||
| 4 | use Sentry::SDK; | ||
| 5 | use Try::Tiny; | ||
| 6 | |||
| 7 | sub register ($self, $app, $conf) { | ||
| 8 | $app->hook( | ||
| 9 | before_server_start => sub ($server, $app) { | ||
| 10 | Sentry::SDK->init($conf); | ||
| 11 | } | ||
| 12 | ); | ||
| 13 | |||
| 14 | $app->hook( | ||
| 15 | around_action => sub ($next, $c, $action, $last) { | ||
| 16 | return unless $last; | ||
| 17 | |||
| 18 | my $req = $c->req; | ||
| 19 | |||
| 20 | Sentry::Hub->get_current_hub()->with_scope(sub ($scope) { | ||
| 21 | my $transaction = Sentry::SDK->start_transaction( | ||
| 22 | { | ||
| 23 | name => $c->match->endpoint->pattern->unparsed || '/', | ||
| 24 | op => 'http.server', | ||
| 25 | }, | ||
| 26 | { | ||
| 27 | request => { | ||
| 28 | url => $req->url->to_string, | ||
| 29 | method => $req->method, | ||
| 30 | query => $req->url->query, | ||
| 31 | headers => $req->headers, | ||
| 32 | } | ||
| 33 | } | ||
| 34 | ); | ||
| 35 | |||
| 36 | Sentry::SDK->configure_scope(sub ($scope) { | ||
| 37 | $scope->set_span($transaction); | ||
| 38 | }); | ||
| 39 | |||
| 40 | try { | ||
| 41 | $next->(); | ||
| 42 | |||
| 43 | } catch { | ||
| 44 | Sentry::SDK->capture_exception($_); | ||
| 45 | $c->reply->exception($_) | ||
| 46 | } finally { | ||
| 47 | $transaction->set_http_status($c->res->code); | ||
| 48 | $transaction->finish(); | ||
| 49 | } | ||
| 50 | |||
| 51 | }); | ||
| 52 | } | ||
| 53 | ); | ||
| 54 | } | ||
| 55 | |||
| 56 | 1; |