Skip to content

Instantly share code, notes, and snippets.

@yannvery
Created February 23, 2021 11:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yannvery/af821af5570a76c0c2615ce6ecd36094 to your computer and use it in GitHub Desktop.
Save yannvery/af821af5570a76c0c2615ce6ecd36094 to your computer and use it in GitHub Desktop.
Extract events from a search error in Bugsnag

Extract error events from Bugsnag

Install bugsnag-api-gem gem

https://github.com/bugsnag/bugsnag-api-ruby

gem install bugsnag-api-gem

Bugsnag token

Get a token from bugsnag interface.

Examples

require 'bugsnag/api'

client = Bugsnag::Api::Client.new(auth_token: "<your-token>")

# Select the right organization before looking for an error.
organizations = client.organizations
org = organizations.first

# Select the right project, take care to the per_page param when you've a lot of projects.
projects = client.projects(org.id, per_page: 100)
project = projects.first

# Prepare filters to find a specific error with events created after 2021-02-23 10:00:00.
filters =  { "event.class" => [{ type: "eq", value: "Connect::Connection::SessionCreationError"}],
             "event.since" => [{ type: "eq", value: "2021-02-23T10:00:00.000Z" }],
}

# Get the error ids.
errors = client.errors(jobteaser.id, nil, filters: filters)
error_ids = errors.map {|e| e.id}

# Prepare a method to deal with the rate limit. 

def with_retry(retries: 5, sleep_time: 15)
  try = 0
  begin
    result = yield
    if result.data.nil?
      result
    elsif result.data.kind_of? Array
      result
    else
      raise "bugsnag fails"
    end
  rescue
    try += 1
    puts "retry #{try}"
    sleep sleep_time
    try <= retries ? retry : nil
  end
end

# Retrieve all events related  to the previous errors.
# Apply the same filters as the error search
# Get the next page when it's necessary
# Deal with the api rate limit.
events = error_ids.inject([]) do |events,error_id|
  # Possible to add the option full_reports: true to get the event details 
  # here, however the request will take a lot of time.
  events = events + client.error_events(jobteaser.id, error_id, filters: filters)
  last_response = client.last_response
  until last_response.rels[:next].nil?
    puts "Events count: #{events.count}"
    last_response = with_retry do |try|
      last_response.rels[:next].get
    end
    events = events + last_response.data
  end
  puts "Error events count: #{events.count}"
  events
end

# Get the detail events
detail_events = events.inject([]) do |de, event|
  event = with_retry do |try|
    client.event(jobteaser.id, event.id)
  end
  puts event[:user].inspect
  de + [event]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment