Class: Philiprehberger::Metric::Counter

Inherits:
Object
  • Object
show all
Defined in:
lib/philiprehberger/metric/counter.rb

Overview

A monotonically increasing counter metric.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, help: '') ⇒ Counter

Returns a new instance of Counter.

Parameters:

  • name (String)

    the metric name

  • help (String) (defaults to: '')

    the help description



15
16
17
18
19
20
# File 'lib/philiprehberger/metric/counter.rb', line 15

def initialize(name, help: '')
  @name = name
  @help = help
  @mutex = Mutex.new
  @values = {}
end

Instance Attribute Details

#helpString (readonly)

Returns the help description.

Returns:

  • (String)

    the help description



11
12
13
# File 'lib/philiprehberger/metric/counter.rb', line 11

def help
  @help
end

#nameString (readonly)

Returns the metric name.

Returns:

  • (String)

    the metric name



8
9
10
# File 'lib/philiprehberger/metric/counter.rb', line 8

def name
  @name
end

Instance Method Details

#get(labels: {}) ⇒ Numeric

Get the current value for a set of labels.

Parameters:

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

    the label set

Returns:

  • (Numeric)

    the current counter value



44
45
46
47
# File 'lib/philiprehberger/metric/counter.rb', line 44

def get(labels: {})
  key = labels.sort.to_h
  @mutex.synchronize { @values[key] || 0 }
end

#increment(amount: 1, labels: {}) ⇒ void

This method returns an undefined value.

Increment the counter.

Counters are monotonic by definition, so negative amount values are rejected and raise Error. Use a Gauge if you need a value that can decrease.

Parameters:

  • amount (Numeric) (defaults to: 1)

    the amount to increment by (default: 1); must be non-negative

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

    optional labels for dimensional metrics

Raises:

  • (Error)

    if amount is negative



31
32
33
34
35
36
37
38
# File 'lib/philiprehberger/metric/counter.rb', line 31

def increment(amount: 1, labels: {})
  raise Error, 'Counter cannot decrease' if amount.negative?

  key = labels.sort.to_h
  @mutex.synchronize do
    @values[key] = (@values[key] || 0) + amount
  end
end

#resetvoid

This method returns an undefined value.

Reset all values.



59
60
61
# File 'lib/philiprehberger/metric/counter.rb', line 59

def reset
  @mutex.synchronize { @values.clear }
end

#snapshotHash

Return a snapshot of all values.

Returns:

  • (Hash)

    labels => value pairs



52
53
54
# File 'lib/philiprehberger/metric/counter.rb', line 52

def snapshot
  @mutex.synchronize { @values.dup }
end

#typeString

Returns the metric type name.

Returns:

  • (String)

    the metric type name



64
65
66
# File 'lib/philiprehberger/metric/counter.rb', line 64

def type
  'counter'
end