Class: NewRelicMetrics

Inherits:
Object
  • Object
show all
Defined in:
lib/fluent/plugin/newrelic_metrics_sender.rb

Instance Method Summary collapse

Constructor Details

#initialize(apikey, url) ⇒ NewRelicMetrics

Returns a new instance of NewRelicMetrics.



6
7
8
9
# File 'lib/fluent/plugin/newrelic_metrics_sender.rb', line 6

def initialize(apikey, url)
  @apikey = apikey
  @url = url
end

Instance Method Details

#send_metrics(metrics_data, http_proxy) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/fluent/plugin/newrelic_metrics_sender.rb', line 11

def send_metrics(metrics_data, http_proxy)
  puts "Sending received metrics data"
  metrics_payload = []
  metrics_payload.push(JSON.parse(metrics_data.to_json))

  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_payload.to_json,
        headers: {params: {'Api-Key' => @apikey}}
    ).execute do |response, request, result|
      case response.code
      when 202
        puts 'Metrics were successfully sent to NewRelic'
        return response.body
      else
        puts "Cannot send metrics to NewRelic url: %s. Received response code: %d"  % [@url, response&.code]
      end
    end
  rescue Net::HTTPClientException => e
    # Handle the HTTP client exception
    puts "An HTTP client error occurred when sending metrics to NewRelic: #{e.message}"
  rescue StandardError => e
    # Handle any other exceptions
    puts "An error occurred when sending metrics to NewRelic: #{e.message}"
  end
end