# frozen_string_literal: true require 'json' require 'rest-client' require 'uri' class DatadogMetrics def initialize(apikey, url) @apikey = apikey @url = url end def add_custom_data(ddtags, record) if ddtags.length() > 0 record_series = record['series'] data_array = [] record_series.each do |interim_data| interim_data['tags'] ||= [] interim_data['tags'].push(*ddtags) data_array << interim_data end record['series'] = data_array return record end return record end def send_metrics(ddtags, record, http_proxy) puts "Additional tags to be added to metrics are", ddtags metrics_data = add_custom_data(ddtags, record) puts "Sending received metrics data" if http_proxy RestClient.proxy = URI.parse(http_proxy) puts "Using http_proxy param to set proxy for request. Proxy url: #{RestClient.proxy}" elsif ENV['HTTP_PROXY'] RestClient.proxy = ENV['HTTP_PROXY'] puts "Using 'HTTP_PROXY' environment variable to set proxy for request. Proxy url: #{RestClient.proxy}" elsif ENV['http_proxy'] RestClient.proxy = ENV['http_proxy'] puts "Using 'http_proxy' environment variable to set proxy for request. Proxy url: #{RestClient.proxy}" elsif ENV['https_proxy'] RestClient.proxy = ENV['https_proxy'] puts "Using 'https_proxy' environment variable to set proxy for request. Proxy url: #{RestClient.proxy}" end begin response = RestClient::Request.new( method: :post, url: @url, payload: metrics_data.to_json, headers: {'DD-API-KEY': @apikey, content_type: :json } ).execute do |response, request, result| case response.code when 202 puts 'Metrics were successfully sent to DataDog' return response.body else puts "Cannot send metrics to DataDog url: %s. Received response code: %d, Response body: %s" % [@url, response.code, response.body] end end rescue Net::HTTPClientException => e # Handle the HTTP client exception puts "An HTTP client error occurred when sending metrics to DataDog: #{e.message}" rescue StandardError => e # Handle any other exceptions puts "An error occurred when sending metrics to DataDog: #{e.message}" end end end