Class: StatsD::Instrument::CompiledMetric::PrecompiledDatagram

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

Overview

A precompiled datagram that can quickly build the final StatsD datagram string using sprintf formatting with cached tag values.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(tag_values, datagram_blueprint, sample_rate) ⇒ PrecompiledDatagram

Returns a new instance of PrecompiledDatagram.

Parameters:

  • tag_values (Array)

    The tag values to cache

  • datagram_blueprint (String)

    The sprintf template

  • sample_rate (Float)

    The sample rate (0.0-1.0)



390
391
392
393
394
# File 'lib/statsd/instrument/compiled_metric.rb', line 390

def initialize(tag_values, datagram_blueprint, sample_rate)
  @tag_values = tag_values
  @datagram_blueprint = datagram_blueprint
  @sample_rate = sample_rate
end

Instance Attribute Details

#datagram_blueprintObject (readonly)

Returns the value of attribute datagram_blueprint.



385
386
387
# File 'lib/statsd/instrument/compiled_metric.rb', line 385

def datagram_blueprint
  @datagram_blueprint
end

#sample_rateObject (readonly)

Returns the value of attribute sample_rate.



385
386
387
# File 'lib/statsd/instrument/compiled_metric.rb', line 385

def sample_rate
  @sample_rate
end

#tag_valuesObject (readonly)

Returns the value of attribute tag_values.



385
386
387
# File 'lib/statsd/instrument/compiled_metric.rb', line 385

def tag_values
  @tag_values
end

Instance Method Details

#to_datagram(value) ⇒ String

Builds the final datagram string by substituting values into the blueprint

Parameters:

  • value (Numeric | Array[Numeric])

    The metric value

Returns:

  • (String)

    The complete StatsD datagram



399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
# File 'lib/statsd/instrument/compiled_metric.rb', line 399

def to_datagram(value)
  packed_value = if value.is_a?(Array)
    value.join(":")
  else
    value.to_s
  end

  # Fast path: no tag values (static metrics)
  return @datagram_blueprint % packed_value if @tag_values.empty?

  # Sanitize string and symbol values (other types handled by sprintf %s)
  values = @tag_values.map do |arg|
    if arg.is_a?(String)
      /[|,]/.match?(arg) ? arg.tr("|,", "") : arg
    elsif arg.is_a?(Symbol)
      str = arg.to_s
      /[|,]/.match?(str) ? str.tr("|,", "") : str
    else
      arg
    end
  end

  # Prepend the metric value
  values.unshift(packed_value)

  # Use sprintf to build the final datagram
  @datagram_blueprint % values
end