Class: TptServerless::Datadog

Inherits:
Object
  • Object
show all
Defined in:
lib/tpt_serverless/datadog.rb

Constant Summary collapse

API_KEY =
(ENV["DD_API_KEY"] && !ENV["DD_API_KEY"].strip.empty?) ? ENV["DD_API_KEY"] : nil
DATADOG_TIMEOUT =

seconds

2
OUR_TIMEOUT =

seconds. slightly longer than DATADOG_TIMEOUT.

3

Instance Method Summary collapse

Constructor Details

#initialize(api_key: API_KEY, datadog_timeout: DATADOG_TIMEOUT, our_timeout: OUR_TIMEOUT) ⇒ Datadog

Returns a new instance of Datadog.



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/tpt_serverless/datadog.rb', line 12

def initialize(api_key: API_KEY, datadog_timeout: DATADOG_TIMEOUT, our_timeout: OUR_TIMEOUT)
  @app_name = ENV.fetch("APP_SERVICE_NAME", "unknownService")
  @stage = ENV.fetch("APP_STAGE", "unknown-stage")
  @host = ENV.fetch("DD_HOSTNAME", nil)
  @our_timeout = our_timeout

  @client = if api_key
    Dogapi::Client.new(
      api_key,         # api key
      nil,             # application_key, not required here
      @host,           # host
      nil,             # device
      true,            # silent
      datadog_timeout, # timeout in seconds
    )
  end
end

Instance Method Details

#inc(metric, amount: 1, tags: []) ⇒ Object



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/tpt_serverless/datadog.rb', line 30

def inc(metric, amount: 1, tags: [])
  # prefix the metric with the app name
  metric = "#{@app_name}.#{metric}"

  tags += ["env:#{@stage}"]
  # change characters not supported by datadog to underscores
  tags.map! { |t| t.gsub(%r([^\w:./-]), "_") }

  # log the metric so that we can correlate between metrics & logs more easily
  logger.info("metric=#{metric} amount=#{amount} tags=#{tags.join(",")}")

  if @client
    begin
      Timeout.timeout(@our_timeout) do
        @client.emit_point(metric, amount, type: "count", tags: tags, host: "aws.lambda")
      end
    rescue Exception => e
      logger.info("WARNING: Failed to emit metric to datadog: #{e.message}")
    end
  end

  nil
end