sentry-ruby icon indicating copy to clipboard operation
sentry-ruby copied to clipboard

Feedback wanted - Add `at_exit` hook for auto exception capturing in scripts

Open sl0thentr0py opened this issue 3 years ago • 5 comments

Currently, automatic capturing only works in rake/rails applications. We want to see if users also want out of the box exception capturing in one-time scripts and other ruby applications.

Raven had this here and python has AtExitIntegration.

sl0thentr0py avatar Feb 16 '22 19:02 sl0thentr0py

I think we'll also need to add a new config to opt-out this feature. Another thing would be to watch out duplicated reporting with other integrations.

st0012 avatar Feb 16 '22 21:02 st0012

I've come up with the following to put on Rails' config/environment.rb

at_exit do
  begin
    next unless (exception = $ERROR_INFO)
    next unless defined?(Sentry)
    next unless Sentry.initialized?

    Sentry.configuration.background_worker_threads = 0
    puts Sentry.capture_exception(exception, level: :fatal).inspect
  rescue => e
    puts e
  end
end

# THE CODE BELOW COMES WITH RAILS

# Load the Rails application.
require_relative "application"

# Initialize the Rails application.
Rails.application.initialize!

This will report to Sentry when the Rails server fails to boot. The same should work for scripts too. I'd love to have this exposed in Sentry as:

class Sentry
  def self.install_at_exit_hook
    at_exit do
      begin
        next unless (exception = $ERROR_INFO)
        next unless defined?(Sentry)
        next unless Sentry.initialized?

        Sentry.configuration.background_worker_threads = 0
        puts Sentry.capture_exception(exception, level: :fatal).inspect
      rescue => e
        puts e
      end
    end
  end
end

rafaelsales avatar Aug 07 '22 20:08 rafaelsales

@rafaelsales Thanks for the feedback! Can you also share what booting issues have been captured by this?

Asking because the exception needs to appear after the SDK is initialized, which happens quite late in the booting process. So it probably mainly catches other initializers' issues? Which it's also helpful but we also need to check other ways to increase the coverage.

st0012 avatar Aug 07 '22 21:08 st0012

@st0012 yes, that's mostly to catch Rails' initialization issues - and for this reason the Sentry.init in my apps are now being called in config/initializers/0_sentry.rb to make sure that errors raised after that will be reported.

I also thought about loading and configuring Sentry even before initializing Rails, but for now I'm happy with the result.

rafaelsales avatar Aug 08 '22 01:08 rafaelsales

I just discovered sentry-cli bash-hook, so I guess I'll add the following to my docker entrypoint bash files:

export SENTRY_DSN='https://[email protected]/0'
eval "$(sentry-cli bash-hook)"

This will cover all other scenarios.

Source: https://docs.sentry.io/product/cli/send-event/#bash-hook

rafaelsales avatar Aug 08 '22 03:08 rafaelsales