Skip to content

Instantly share code, notes, and snippets.

@fallwith
Created August 22, 2022 20:07
Show Gist options
  • Save fallwith/5e5eca4b1be0e49b69656942e4f30ae9 to your computer and use it in GitHub Desktop.
Save fallwith/5e5eca4b1be0e49b69656942e4f30ae9 to your computer and use it in GitHub Desktop.
Use newrelic_rpm to manually notice an error
#!/usr/bin/env ruby
# frozen_string_literal: true
# The New Relic Ruby agent can be instructed to manually notice an error by
# using the public NewRelic::Agent.notice_error method.
#
# NewRelic::Agent.notice_error does not require that a New Relic Ruby agent
# transaction exist. It simply requires that the New Relic Ruby agent be
# connected, which itself requires the use of a valid license key.
#
# After an error has been noticed, the New Relic Ruby agent must be given
# enough time for a full harvest cycle to complete. The agent sends data up to
# New Relic's servers in batches, so enough time must be given for a batch to
# be put together and sent up before the agent is shut down.
#
# The following code demonstrates requiring the New Relic Ruby agent gem,
# connecting the agent, noticing an error, giving the agent enough time to
# report the error, and then shutting down the agent.
#
# To run this code...
#
# At an interactive IRB/Pry prompt:
# 1. Make sure a valid `newrelic.yml` file exists at PWD
# 2. Paste the code below into the prompt
#
# As a standlone Ruby script:
# 1. Save this code somewhere as notice_error.rb
# 2. Make sure the newly created file is executable:
# $ chmod 755 notice_error.rb
# 3. Make sure a valid `newrelic.yml` file exists alongside
# the `notice_error.rb` file in the same directory
# 4. Execute the file:
# $ ./notice_error.rb
require 'newrelic_rpm'
NewRelic::Agent.manual_start
# make sure the agent is connected before interacting with it
puts 'Waiting for the New Relic Ruby agent to connect...'
sleep 0.1 until NewRelic::Agent.agent.connected?
puts 'Noticing an error...'
NewRelic::Agent.notice_error StandardError.new("testing - #{Time.now}")
# make sure the agent has had enough time to send up data
wait_time = 60
puts "Giving the New Relic Ruby agent #{wait_time} seconds to report the error..."
sleep wait_time
puts 'Shutting down the New Relic Ruby agent...'
NewRelic::Agent.shutdown
puts 'Done.'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment