Sha256: c35fb0378fbaf4a7c4ff4bfebf7221e0a45c825d1208b49c405439a4fa7e0986

Contents?: true

Size: 1.5 KB

Versions: 8

Compression:

Stored size: 1.5 KB

Contents

require 'thread'
require 'logger'


module Anschel
  class Stats

    def initialize logger, interval=60
      @logger   = logger
      @interval = interval
      @stats    = Hash.new
      @lock     = Mutex.new

      Thread.new do
        loop do
          sleep @interval
          report_and_reset
        end
      end

      @logger.info event: 'stats-loaded'
    end


    def create name, default=0
      with_lock do
        stats[name] = {}
        stats[name].default = default
        stats
      end
    end

    def delete name
      with_lock do
        stats.delete name
      end
    end

    def inc name, by=1
      with_lock do
        stats[name][:val] += by
      end
    end

    def dec name, by=1
      with_lock do
        stats[name][:val] -= by
      end
    end

    def set name, to
      with_lock do
        stats[name][:val] = to
      end
    end

    def get name
      with_lock do
        stats[name][:val]
      end
    end


  private
    attr_reader :stats

    def with_lock &block
      @lock.synchronize do
        yield
      end
    end

    def report_and_reset
      ready_stats = with_lock do
        stats.keys.flat_map do |k|
          v = stats[k].delete(:val)
          v ||= stats[k].default
          stats[k][:val] = stats[k].default
          [
            [ k, v ],
            [ "#{k}_rate", 1.0 * v / @interval ]
          ]
        end
      end

      @logger.info \
        event: 'stats',
        interval: @interval,
        stats: Hash[ready_stats]
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
anschel-0.6.1 lib/anschel/stats.rb
anschel-0.6.0 lib/anschel/stats.rb
anschel-0.5.0 lib/anschel/stats.rb
anschel-0.4.1 lib/anschel/stats.rb
anschel-0.4.0 lib/anschel/stats.rb
anschel-0.3.2 lib/anschel/stats.rb
anschel-0.3.1 lib/anschel/stats.rb
anschel-0.3.0 lib/anschel/stats.rb