stayallive / wp-sentry

A (unofficial) WordPress plugin reporting PHP and JavaScript errors to Sentry.
https://wordpress.org/plugins/wp-sentry-integration/
MIT License
305 stars 48 forks source link

Don't capture all plugin errors #90

Closed marcwieland95 closed 3 years ago

marcwieland95 commented 3 years ago

Hey there,

first of all. The plugin works great. No issues so far.

I'm wondering if there is a possibility to remove exceptions of plugins (code I don't control by myself). We have the problem that our logs are just too much and most of them are irrelevant since we can't change the plugins.

Thanks for your input Cheers Marc

stayallive commented 3 years ago

Hi Marc,

You can but there is no "simple option" but we have plenty of hooks in the Sentry SDK to use.

I've written about it here: https://wordpress.org/support/topic/enable-sentry-for-specific-plugin/#post-14155498.

Let me know if that helps or if you get stuck somewhere!

marcwieland95 commented 3 years ago

Amazing. That helped a lot.

For documentation purpose

I created this little snippet to check if there are some parts within my code in the stack trace. Attention: there's a PHP 8.x function used in this snippet.

add_filter('wp_sentry_options', function onlyTrackOwnCode(\Sentry\Options $options) {
    $options->setBeforeSendCallback(function (\Sentry\Event $event) {
        $stacktrace = $event->getExceptions()[0]->getStacktrace();
        $ourCode = false; // we don't own the code, so don't track it

        foreach ($stacktrace->getFrames() as $frame) {
            if(
                str_contains($frame->getFile(), 'themes/THEME_NAME') ||
                str_contains($frame->getFile(), 'plugins/PLUGIN_NAME')
            ) {
                $ourCode = true; // send event to Sentry
            }
        }

        return $ourCode ? $event : null;

    });
});

As mentioned in the linked ticket, it's important to run this filter at a very early stage.

stayallive commented 3 years ago

Awesome, thanks for sharing!

Would you mind if I add a (slightly modified) version of this to the README for others looking for a solution?

marcwieland95 commented 3 years ago

Sure. Go for it. It's not the nicest code ever and not greatly tested. But should work

stayallive commented 3 years ago

I've made it a little more robust and also added a fallback for older PHP versions.

Take a look: https://github.com/stayallive/wp-sentry#capturing-errors-only-from-certain-theme-andor-plugin.

Thanks again for sharing!