Created
March 31, 2023 21:49
-
-
Save fallwith/d9ba631676eec0f39fc71358e3473dd1 to your computer and use it in GitHub Desktop.
A standalone example of using the New Relic Ruby agent's increment_metric public API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
# frozen_string_literal: true | |
# A standalone example of using the New Relic Ruby agent's | |
# NewRelic::Agent.increment_metric public API | |
# | |
# INSTRUCTIONS: | |
# - Place this file somewhere. It can be called something like `increment.rb` | |
# | |
# - Either place a newrelic.yml file in the same directory as this file OR | |
# export the NEW_RELIC_LICENSE_KEY environment variable. | |
# If using a newrelic.yml file, it should look like this: | |
# # newrelic.yml | |
# development: | |
# license_key: <YOUR KEY> | |
# | |
# - Run this script with `ruby increment.rb` | |
# (or make it executable and use `./increment.rb`) | |
require 'bundler/inline' | |
puts 'Checking out the Ruby agent with Bundler...' | |
gemfile do | |
source 'https://rubygems.org' | |
gem 'newrelic_rpm' | |
end | |
class Increment | |
SHUTDOWN_SLEEP = 60 | |
LOG_FILE = 'log/newrelic_agent.log' | |
METRIC_NAME_PROCESS = 'Custom/process/1138' | |
METRIC_NAME_DELIVER = 'Custom/deliver/1138' | |
COUNT_PROCESS = 1500 | |
COUNT_DELIVER = 1400 | |
def go | |
wait_for_connection | |
increment_metrics | |
graceful_shutdown | |
check_log | |
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_FILE} for WARN/ERROR" | |
sleep 1 until NewRelic::Agent.agent.connected? | |
end | |
def increment_metrics | |
COUNT_PROCESS.times { ::NewRelic::Agent.increment_metric(METRIC_NAME_PROCESS) } | |
COUNT_DELIVER.times { ::NewRelic::Agent.increment_metric(METRIC_NAME_DELIVER) } | |
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 | |
def check_log | |
if log_data =~ %r{INFO : Reporting to: (https://.*?)(\s+|$)} | |
puts "Data was submitted to #{Regexp.last_match(1)}" | |
else | |
puts "Couldn't glean a URL from the #{LOG_FILE} file. Check that file for WARN/ERROR" | |
end | |
end | |
def log_data | |
return File.read(LOG_FILE) if File.exist?(LOG_FILE) | |
puts "The agent log file #{LOG_FILE} didn't appear to get created." | |
'' | |
end | |
end | |
Increment.new.go if $PROGRAM_NAME == __FILE__ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment