Class: Datadog::Statsd

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

Defined Under Namespace

Classes: Batch, Connection, UDPConnection, UDSConnection

Constant Summary collapse

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
MAX_EVENT_SIZE =
8 * 1024
COUNTER_TYPE =
'c'.freeze
GAUGE_TYPE =
'g'.freeze
HISTOGRAM_TYPE =
'h'.freeze
DISTRIBUTION_TYPE =
'd'.freeze
TIMING_TYPE =
'ms'.freeze
SET_TYPE =
's'.freeze
VERSION =
"4.4.0".freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(host = nil, port = nil, namespace: nil, tags: nil, max_buffer_bytes: 8192, socket_path: nil, logger: nil, sample_rate: nil) ⇒ Statsd

Returns a new instance of Statsd.

Parameters:

  • host (String) (defaults to: nil)

    your statsd host

  • port (Integer) (defaults to: nil)

    your statsd port

  • [String] (Hash)

    a customizable set of options

  • [Array<String>|Hash] (Hash)

    a customizable set of options

  • [Logger] (Hash)

    a customizable set of options

  • [Integer] (Hash)

    a customizable set of options

  • [Float] (Hash)

    a customizable set of options



223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
# File 'lib/datadog/statsd.rb', line 223

def initialize(
  host = nil,
  port = nil,
  namespace: nil,
  tags: nil,
  max_buffer_bytes: 8192,
  socket_path: nil,
  logger: nil,
  sample_rate: nil
)
  if socket_path.nil?
    @connection = UDPConnection.new(host, port, logger)
  else
    @connection = UDSConnection.new(socket_path, logger)
  end
  @logger = logger

  @namespace = namespace
  @prefix = @namespace ? "#{@namespace}.".freeze : nil

  @sample_rate = sample_rate

  unless tags.nil? or tags.is_a? Array or tags.is_a? Hash
    raise ArgumentError, 'tags must be a Array<String> or a Hash'
  end

  tags = tag_hash_to_array(tags) if tags.is_a? Hash
  @tags = (tags || []).compact.map! {|tag| escape_tag_content(tag)}

  # append the entity id to tags if DD_ENTITY_ID env var is not nil
  @tags << 'dd.internal.entity_id:' + escape_tag_content(ENV.fetch('DD_ENTITY_ID', nil)) unless ENV.fetch('DD_ENTITY_ID', nil).nil?

  @batch = Batch.new @connection, max_buffer_bytes
end

Instance Attribute Details

#bufferObject (readonly)

Buffer containing the statsd message before they are sent in batch



204
205
206
# File 'lib/datadog/statsd.rb', line 204

def buffer
  @buffer
end

#connectionObject (readonly)

Connection



213
214
215
# File 'lib/datadog/statsd.rb', line 213

def connection
  @connection
end

#max_buffer_bytesObject (readonly)

Maximum buffer size in bytes before it is flushed



207
208
209
# File 'lib/datadog/statsd.rb', line 207

def max_buffer_bytes
  @max_buffer_bytes
end

#namespaceObject (readonly)

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



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

def namespace
  @namespace
end

#sample_rateObject (readonly)

Default sample rate



210
211
212
# File 'lib/datadog/statsd.rb', line 210

def sample_rate
  @sample_rate
end

#tagsObject (readonly)

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



201
202
203
# File 'lib/datadog/statsd.rb', line 201

def tags
  @tags
end

Class Method Details

.open(*args) ⇒ Object

yield a new instance to a block and close it when done for short-term use-cases that don’t want to close the socket manually



260
261
262
263
264
265
# File 'lib/datadog/statsd.rb', line 260

def self.open(*args)
  instance = new(*args)
  yield instance
ensure
  instance.close
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


450
451
452
# File 'lib/datadog/statsd.rb', line 450

def batch
  @batch.open { yield self }
end

#closeObject

Close the underlying socket



455
456
457
# File 'lib/datadog/statsd.rb', line 455

def close
  @connection.close
end

#count(stat, count, opts = EMPTY_OPTIONS) ⇒ 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: EMPTY_OPTIONS)

    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



302
303
304
305
# File 'lib/datadog/statsd.rb', line 302

def count(stat, count, opts=EMPTY_OPTIONS)
  opts = {:sample_rate => opts} if opts.is_a? Numeric
  send_stats stat, count, COUNTER_TYPE, opts
end

#decrement(stat, opts = EMPTY_OPTIONS) ⇒ Object

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

Parameters:

  • stat (String)

    stat name

  • opts (Hash) (defaults to: EMPTY_OPTIONS)

    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:



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

def decrement(stat, opts=EMPTY_OPTIONS)
  opts = {:sample_rate => opts} if opts.is_a? Numeric
  decr_value = - opts.fetch(:by, 1)
  count stat, decr_value, opts
end

#distribution(stat, value, opts = EMPTY_OPTIONS) ⇒ Object

Sends a value to be tracked as a distribution to the statsd server. Note: Distributions are a beta feature of Datadog and not generally available. Distributions must be specifically enabled for your organization.

Examples:

Report the current user count:

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

Parameters:

  • stat (String)

    stat name.

  • value (Numeric)

    distribution value.

  • opts (Hash) (defaults to: EMPTY_OPTIONS)

    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



350
351
352
# File 'lib/datadog/statsd.rb', line 350

def distribution(stat, value, opts=EMPTY_OPTIONS)
  send_stats stat, value, DISTRIBUTION_TYPE, opts
end

#event(title, text, opts = EMPTY_OPTIONS) ⇒ 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 newlines (\n)

  • opts (Hash) (defaults to: EMPTY_OPTIONS)

    the additional data about the event

Options Hash (opts):

  • :date_happened (Integer, String, 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



438
439
440
# File 'lib/datadog/statsd.rb', line 438

def event(title, text, opts=EMPTY_OPTIONS)
  send_stat format_event(title, text, opts)
end

#gauge(stat, value, opts = EMPTY_OPTIONS) ⇒ 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: EMPTY_OPTIONS)

    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



320
321
322
323
# File 'lib/datadog/statsd.rb', line 320

def gauge(stat, value, opts=EMPTY_OPTIONS)
  opts = {:sample_rate => opts} if opts.is_a? Numeric
  send_stats stat, value, GAUGE_TYPE, opts
end

#histogram(stat, value, opts = EMPTY_OPTIONS) ⇒ 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: EMPTY_OPTIONS)

    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



334
335
336
# File 'lib/datadog/statsd.rb', line 334

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

#increment(stat, opts = EMPTY_OPTIONS) ⇒ Object

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

Parameters:

  • stat (String)

    stat name

  • opts (Hash) (defaults to: EMPTY_OPTIONS)

    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:



275
276
277
278
279
# File 'lib/datadog/statsd.rb', line 275

def increment(stat, opts=EMPTY_OPTIONS)
  opts = {:sample_rate => opts} if opts.is_a? Numeric
  incr_value = opts.fetch(:by, 1)
  count stat, incr_value, opts
end

#service_check(name, status, opts = EMPTY_OPTIONS) ⇒ Object

Examples:

Report a critical service check status

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


416
417
418
# File 'lib/datadog/statsd.rb', line 416

def service_check(name, status, opts=EMPTY_OPTIONS)
  send_stat format_service_check(name, status, opts)
end

#set(stat, value, opts = EMPTY_OPTIONS) ⇒ 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: EMPTY_OPTIONS)

    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



400
401
402
403
# File 'lib/datadog/statsd.rb', line 400

def set(stat, value, opts=EMPTY_OPTIONS)
  opts = {:sample_rate => opts} if opts.is_a? Numeric
  send_stats stat, value, SET_TYPE, opts
end

#time(stat, opts = EMPTY_OPTIONS) { ... } ⇒ 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: EMPTY_OPTIONS)

    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:



382
383
384
385
386
387
388
389
# File 'lib/datadog/statsd.rb', line 382

def time(stat, opts=EMPTY_OPTIONS)
  opts = {:sample_rate => opts} if opts.is_a? Numeric
  start = (PROCESS_TIME_SUPPORTED ? Process.clock_gettime(Process::CLOCK_MONOTONIC) : Time.now.to_f)
  return yield
ensure
  finished = (PROCESS_TIME_SUPPORTED ? Process.clock_gettime(Process::CLOCK_MONOTONIC) : Time.now.to_f)
  timing(stat, ((finished - start) * 1000).round, opts)
end

#timing(stat, ms, opts = EMPTY_OPTIONS) ⇒ 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: EMPTY_OPTIONS)

    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



364
365
366
367
# File 'lib/datadog/statsd.rb', line 364

def timing(stat, ms, opts=EMPTY_OPTIONS)
  opts = {:sample_rate => opts} if opts.is_a? Numeric
  send_stats stat, ms, TIMING_TYPE, opts
end