Class: Datadog::Statsd

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

Constant Summary collapse

DEFAULT_HOST =
'127.0.0.1'
DEFAULT_PORT =
8125
OPTS_KEYS =

Create a dictionary to assign a key to every parameter’s name, except for tags (treated differently) Goal: Simple and fast to add some other parameters

{
  :date_happened     => :d,
  :hostname          => :h,
  :aggregation_key   => :k,
  :priority          => :p,
  :source_type_name  => :s,
  :alert_type        => :t,
}
SC_OPT_KEYS =

Service check options

{
  :timestamp  => 'd:'.freeze,
  :hostname   => 'h:'.freeze,
  :tags       => '#'.freeze,
  :message    => 'm:'.freeze,
}
OK =
0
WARNING =
1
CRITICAL =
2
UNKNOWN =
3
COUNTER_TYPE =
'c'.freeze
GAUGE_TYPE =
'g'.freeze
HISTOGRAM_TYPE =
'h'.freeze
TIMING_TYPE =
'ms'.freeze
SET_TYPE =
's'.freeze

Class Attribute Summary collapse

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(host = DEFAULT_HOST, port = DEFAULT_PORT, opts = {}, max_buffer_size = 50) ⇒ Statsd

Returns a new instance of Statsd.

Parameters:

  • host (String) (defaults to: DEFAULT_HOST)

    your statsd host

  • port (Integer) (defaults to: DEFAULT_PORT)

    your statsd port

  • opts (Hash) (defaults to: {})

    a customizable set of options

Options Hash (opts):

  • :namespace (String)

    set a namespace to be prepended to every metric name

  • :tags (Array<String>)

    tags to be added to every metric



91
92
93
94
95
96
97
98
99
100
# File 'lib/datadog/statsd.rb', line 91

def initialize(host = DEFAULT_HOST, port = DEFAULT_PORT, opts = {}, max_buffer_size=50)
  self.host, self.port = host, port
  @prefix = nil
  @socket = connect_to_socket(host, port)
  self.namespace = opts[:namespace]
  self.tags = opts[:tags]
  @buffer = Array.new
  self.max_buffer_size = max_buffer_size
  @should_batch = false
end

Class Attribute Details

.loggerObject

Set to a standard logger instance to enable debug logging.



79
80
81
# File 'lib/datadog/statsd.rb', line 79

def logger
  @logger
end

Instance Attribute Details

#bufferObject (readonly)

Buffer containing the statsd message before they are sent in batch



72
73
74
# File 'lib/datadog/statsd.rb', line 72

def buffer
  @buffer
end

#hostObject

StatsD host. Defaults to 127.0.0.1.



59
60
61
# File 'lib/datadog/statsd.rb', line 59

def host
  @host
end

#max_buffer_sizeObject

Maximum number of metrics in the buffer before it is flushed



75
76
77
# File 'lib/datadog/statsd.rb', line 75

def max_buffer_size
  @max_buffer_size
end

#namespaceObject

A namespace to prepend to all statsd calls. Defaults to no namespace.



56
57
58
# File 'lib/datadog/statsd.rb', line 56

def namespace
  @namespace
end

#portObject

StatsD port. Defaults to 8125.



62
63
64
# File 'lib/datadog/statsd.rb', line 62

def port
  @port
end

#should_batchObject (readonly)

True if we should batch up data before sending it, or false if we want to send data immediately.



69
70
71
# File 'lib/datadog/statsd.rb', line 69

def should_batch
  @should_batch
end

#tagsObject

Global tags to be added to every statsd call. Defaults to no tags.



65
66
67
# File 'lib/datadog/statsd.rb', line 65

def tags
  @tags
end

Class Method Details

.VERSIONObject

Return the current version of the library.



83
84
85
# File 'lib/datadog/statsd.rb', line 83

def self.VERSION
  "3.0.0"
end

Instance Method Details

#batchObject

Send several metrics in the same UDP Packet They will be buffered and flushed when the block finishes

Examples:

Send several metrics in one packet:

$statsd.batch do |s|
   s.gauge('users.online',156)
   s.increment('page.views')
 end


305
306
307
308
309
310
311
# File 'lib/datadog/statsd.rb', line 305

def batch()
  @should_batch = true
  yield self
  flush_buffer
ensure
  @should_batch = false
end

#closeObject

Close the underlying socket



338
339
340
# File 'lib/datadog/statsd.rb', line 338

def close()
  @socket.close
end

#count(stat, count, opts = {}) ⇒ Object

Sends an arbitrary count for the given stat to the statsd server.

Parameters:

  • stat (String)

    stat name

  • count (Integer)

    count

  • opts (Hash) (defaults to: {})

    the options to create the metric with

Options Hash (opts):

  • :sample_rate (Numeric)

    sample rate, 1 for always

  • :tags (Array<String>)

    An array of tags



153
154
155
# File 'lib/datadog/statsd.rb', line 153

def count(stat, count, opts={})
  send_stats stat, count, COUNTER_TYPE, opts
end

#decrement(stat, opts = {}) ⇒ Object

Sends a decrement (count = -1) for the given stat to the statsd server.

Parameters:

  • stat (String)

    stat name

  • opts (Hash) (defaults to: {})

    the options to create the metric with

Options Hash (opts):

  • :sample_rate (Numeric)

    sample rate, 1 for always

  • :tags (Array<String>)

    An array of tags

  • :by (Numeric)

    decrement value, default 1

See Also:



141
142
143
144
# File 'lib/datadog/statsd.rb', line 141

def decrement(stat, opts={})
  decr_value = - opts.fetch(:by, 1)
  count stat, decr_value, opts
end

#event(title, text, opts = {}) ⇒ Object

This end point allows you to post events to the stream. You can tag them, set priority and even aggregate them with other events.

Aggregation in the stream is made on hostname/event_type/source_type/aggregation_key. If there’s no event type, for example, then that won’t matter; it will be grouped with other events that don’t have an event type.

Examples:

Report an awful event:

$statsd.event('Something terrible happened', 'The end is near if we do nothing', :alert_type=>'warning', :tags=>['end_of_times','urgent'])

Parameters:

  • title (String)

    Event title

  • text (String)

    Event text. Supports n

  • opts (Hash) (defaults to: {})

    the additional data about the event

Options Hash (opts):

  • :date_happened (Integer, nil) — default: nil

    Assign a timestamp to the event. Default is now when none

  • :hostname (String, nil) — default: nil

    Assign a hostname to the event.

  • :aggregation_key (String, nil) — default: nil

    Assign an aggregation key to the event, to group it with some others

  • :priority (String, nil) — default: 'normal'

    Can be “normal” or “low”

  • :source_type_name (String, nil) — default: nil

    Assign a source type to the event

  • :alert_type (String, nil) — default: 'info'

    Can be “error”, “warning”, “info” or “success”.

  • :tags (Array<String>)

    tags to be added to every metric



290
291
292
293
294
295
# File 'lib/datadog/statsd.rb', line 290

def event(title, text, opts={})
  event_string = format_event(title, text, opts)
  raise "Event #{title} payload is too big (more that 8KB), event discarded" if event_string.length > 8 * 1024

  send_to_socket event_string
end

#format_event(title, text, opts = {}) ⇒ Object



313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
# File 'lib/datadog/statsd.rb', line 313

def format_event(title, text, opts={})
  escaped_title = escape_event_content(title)
  escaped_text = escape_event_content(text)
  event_string_data = "_e{#{escaped_title.length},#{escaped_text.length}}:#{escaped_title}|#{escaped_text}"

  # We construct the string to be sent by adding '|key:value' parts to it when needed
  # All pipes ('|') in the metadata are removed. Title and Text can keep theirs
  OPTS_KEYS.each do |key, shorthand_key|
    if key != :tags && opts[key]
      value = remove_pipes(opts[key])
      event_string_data << "|#{shorthand_key}:#{value}"
    end
  end

  # Tags are joined and added as last part to the string to be sent
  full_tags = (tags + (opts[:tags] || [])).map {|tag| escape_tag_content(tag) }
  unless full_tags.empty?
    event_string_data << "|##{full_tags.join(COMMA)}"
  end

  raise "Event #{title} payload is too big (more that 8KB), event discarded" if event_string_data.length > 8192 # 8 * 1024 = 8192
  return event_string_data
end

#format_service_check(name, status, opts = {}) ⇒ Object



250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
# File 'lib/datadog/statsd.rb', line 250

def format_service_check(name, status, opts={})
  sc_string = "_sc|#{name}|#{status}"

  SC_OPT_KEYS.each do |key, shorthand_key|
    next unless opts[key]

    if key == :tags
      tags = opts[:tags].map {|tag| escape_tag_content(tag) }
      tags = "#{tags.join(COMMA)}" unless tags.empty?
      sc_string << "|##{tags}"
    elsif key == :message
      message = remove_pipes(opts[:message])
      escaped_message = escape_service_check_message(message)
      sc_string << "|m:#{escaped_message}"
    else
      value = remove_pipes(opts[key])
      sc_string << "|#{shorthand_key}#{value}"
    end
  end
  return sc_string
end

#gauge(stat, value, opts = {}) ⇒ Object

Sends an arbitary gauge value for the given stat to the statsd server.

This is useful for recording things like available disk space, memory usage, and the like, which have different semantics than counters.

Examples:

Report the current user count:

$statsd.gauge('user.count', User.count)

Parameters:

  • stat (String)

    stat name.

  • value (Numeric)

    gauge value.

  • opts (Hash) (defaults to: {})

    the options to create the metric with

Options Hash (opts):

  • :sample_rate (Numeric)

    sample rate, 1 for always

  • :tags (Array<String>)

    An array of tags



170
171
172
# File 'lib/datadog/statsd.rb', line 170

def gauge(stat, value, opts={})
  send_stats stat, value, GAUGE_TYPE, opts
end

#histogram(stat, value, opts = {}) ⇒ Object

Sends a value to be tracked as a histogram to the statsd server.

Examples:

Report the current user count:

$statsd.histogram('user.count', User.count)

Parameters:

  • stat (String)

    stat name.

  • value (Numeric)

    histogram value.

  • opts (Hash) (defaults to: {})

    the options to create the metric with

Options Hash (opts):

  • :sample_rate (Numeric)

    sample rate, 1 for always

  • :tags (Array<String>)

    An array of tags



183
184
185
# File 'lib/datadog/statsd.rb', line 183

def histogram(stat, value, opts={})
  send_stats stat, value, HISTOGRAM_TYPE, opts
end

#increment(stat, opts = {}) ⇒ Object

Sends an increment (count = 1) for the given stat to the statsd server.

Parameters:

  • stat (String)

    stat name

  • opts (Hash) (defaults to: {})

    the options to create the metric with

Options Hash (opts):

  • :sample_rate (Numeric)

    sample rate, 1 for always

  • :tags (Array<String>)

    An array of tags

  • :by (Numeric)

    increment value, default 1

See Also:



128
129
130
131
# File 'lib/datadog/statsd.rb', line 128

def increment(stat, opts={})
  incr_value = opts.fetch(:by, 1)
  count stat, incr_value, opts
end

#service_check(name, status, opts = {}) ⇒ Object

Examples:

Report a critical service check status

$statsd.service_check('my.service.check', Statsd::CRITICAL, :tags=>['urgent'])


245
246
247
248
# File 'lib/datadog/statsd.rb', line 245

def service_check(name, status, opts={})
  service_check_string = format_service_check(name, status, opts)
  send_to_socket service_check_string
end

#set(stat, value, opts = {}) ⇒ Object

Sends a value to be tracked as a set to the statsd server.

Examples:

Record a unique visitory by id:

$statsd.set('visitors.uniques', User.id)

Parameters:

  • stat (String)

    stat name.

  • value (Numeric)

    set value.

  • opts (Hash) (defaults to: {})

    the options to create the metric with

Options Hash (opts):

  • :sample_rate (Numeric)

    sample rate, 1 for always

  • :tags (Array<String>)

    An array of tags



229
230
231
# File 'lib/datadog/statsd.rb', line 229

def set(stat, value, opts={})
  send_stats stat, value, SET_TYPE, opts
end

#time(stat, opts = {}) { ... } ⇒ Object

Reports execution time of the provided block using #timing.

If the block fails, the stat is still reported, then the error is reraised

Examples:

Report the time (in ms) taken to activate an account

$statsd.time('account.activate') { @account.activate! }

Parameters:

  • stat (String)

    stat name

  • opts (Hash) (defaults to: {})

    the options to create the metric with

Options Hash (opts):

  • :sample_rate (Numeric)

    sample rate, 1 for always

  • :tags (Array<String>)

    An array of tags

Yields:

  • The operation to be timed

See Also:



214
215
216
217
218
219
# File 'lib/datadog/statsd.rb', line 214

def time(stat, opts={})
  start = Time.now
  return yield
ensure
  time_since(stat, start, opts)
end

#timing(stat, ms, opts = {}) ⇒ Object

Sends a timing (in ms) for the given stat to the statsd server. The sample_rate determines what percentage of the time this report is sent. The statsd server then uses the sample_rate to correctly track the average timing for the stat.

Parameters:

  • stat (String)

    stat name

  • ms (Integer)

    timing in milliseconds

  • opts (Hash) (defaults to: {})

    the options to create the metric with

Options Hash (opts):

  • :sample_rate (Numeric)

    sample rate, 1 for always

  • :tags (Array<String>)

    An array of tags



197
198
199
# File 'lib/datadog/statsd.rb', line 197

def timing(stat, ms, opts={})
  send_stats stat, ms, TIMING_TYPE, opts
end