Skip to content

Instantly share code, notes, and snippets.

@fallwith
Created July 19, 2023 17:12
Show Gist options
  • Save fallwith/a9b05979a12d1446999fb46f2106c4e5 to your computer and use it in GitHub Desktop.
Save fallwith/a9b05979a12d1446999fb46f2106c4e5 to your computer and use it in GitHub Desktop.
New Relic Ruby agent demonstration of the notice_error API inside a transaction
#!/usr/bin/env ruby
# frozen_string_literal: true
# INSTRUCTIONS:
# - Place this file somewhere. It can be called something like `test.rb`
#
# - Either place a newrelic.yml file in the same directory as this file OR
# export the NEW_RELIC_LICENSE_KEY environment variable. For a
# non-production host, also export the NEW_RELIC_HOST environment variable.
#
# If using a newrelic.yml file, it should look like this:
# # newrelic.yml
# development:
# license_key: <YOUR KEY>
# host: <YOUR ENVIRONMENT>-collector.newrelic.com
#
# - Run this script with `ruby test.rb`
# (or make it executable and use `./test.rb`)
require 'bundler/inline'
puts 'Cloning the Ruby agent git repo with Bundler...'
gemfile do
source 'https://rubygems.org'
gem 'newrelic_rpm', git: 'https://github.com/newrelic/newrelic-ruby-agent', branch: 'dev'
end
# Kaboom - NR error reporting example class
class Kaboom
SHUTDOWN_SLEEP = 60
def explode
wait_for_connection
create_some_errors
graceful_shutdown
end
private
def wait_for_connection
puts 'Waiting for New Relic agent to connect...'
puts 'NOTE: If the connection process takes long, kill the script and check log/newrelic_agent.log for WARN/ERROR'
sleep 1 until NewRelic::Agent.agent.connected?
end
def create_some_errors
NewRelic::Agent::Tracer.in_transaction(partial_name: 'ErrorTesting/create_some_errors', category: :task) do
puts 'Generating some errors inside a transaction...'
random_strings.each do |string|
NewRelic::Agent.notice_error(StandardError.new("Phony error '#{string}' encountered!"))
end
end
end
def random_strings(count = 5, length = 5)
count.times.map { Array.new(length) { ('a'..'z').to_a.sample }.join }
end
def graceful_shutdown
puts "Giving the agent harvester time to send data up to the collector (sleep = #{SHUTDOWN_SLEEP} secs)..."
sleep SHUTDOWN_SLEEP
puts 'Shutting down New Relic agent...'
NewRelic::Agent.shutdown
end
end
Kaboom.new.explode
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment