Yet another case of trying to find an answer to a very particular problem, coming up empty, solving it myself, and posting about it for future generations.
Update 2023-04-01
Thanks to Michi Hoffmann, this is now even easier to manage with a built in ignore_transactions
configuration option now available as of release 3.17.0 of sentry-php!
Now, instead of using the before_send_transaction
config I swapped to using ignore_transactions
and my code changed to the following:
'ignore_transactions' => ['/_debugbar', '/monitoring', '/pleaseignoreme'],
Below is the original post for posterity, but with the addition above that solution is no longer necessary.
The Problem
I have a couple Laravel PHP routes that are triggered quite often, both are very specific to other site monitoring (is the site down?) and session management (am I still logged in?). These being utility routes that don’t serve a user-facing purpose, I don’t need any additional logging details about them from Sentry.
Can I prevent the transaction from being sent to Sentry before it even leaves my server? I tried searching terms like “sentry laravel ignore route” and “sentry control transactions from PHP” to no avail so I got to work.
The Solution
In my searches, I did find this helpful documentation for before_send_transaction specifically for Laravel. It’s an optional addition to the /config/sentry.php
configuration. In it, you can define any logic you want to return null
in preferred situations. This null return will lead to the event being discarded. Bingo!
Here’s the code I worked up.
'before_send_transaction' => function (
\Sentry\Event $transaction
): ?\Sentry\Event {
$ignore = ['_debugbar', 'monitoring', 'pleaseignoreme'];
$request = $transaction->getRequest();
$check = array_filter($ignore, function ($url) use ($request) {
if (stripos($request['url'], $url) !== false) {
return true;
}
});
if (count($check) > 0) {
return null;
}
return $transaction;
},
Here’s what it’s doing:
-
$ignore
is the array of URL key terms I want to ignore, this is all you need to edit. Add any URL segments that you’d prefer not to be logged by Sentry and you good to go -
$request
is the request details coming from the packaged$transaction
generated by Sentry. In it is the full URL that we use to test against -
$check
was my method of iterating through the ignore list and checking for a match. This filters the$ignore
array down to just matches. - We then see if the count of
$check
is greater than zero, if so then one of the routes matched and we want to returnnull
to ignore this transaction. Otherwise, return as normal.
That’s it!
Pretty simple, but it took a bit of digging through documentation to find before_send_transaction
and through the Sentry package to see what $transaction
contained so I’m hoping to spare the next dev that bit of trouble.
Onward and upward! 🚀
Top comments (0)