lib/statsd.rb in dogstatsd-ruby-1.1.0 vs lib/statsd.rb in dogstatsd-ruby-1.2.0

- old
+ new

@@ -10,53 +10,70 @@ # $statsd.timing 'page.load', 320 # $statsd.gauge 'users.online', 100 # @example Use {#time} to time the execution of a block # $statsd.time('account.activate') { @account.activate! } # @example Create a namespaced statsd client and increment 'account.activate' -# statsd = Statsd.new('localhost').tap{|sd| sd.namespace = 'account'} +# statsd = Statsd.new 'localhost', 8125, :namespace => 'account' # statsd.increment 'activate' +# @example Create a statsd client with global tags +# statsd = Statsd.new 'localhost', 8125, :tags => 'tag1:true' class Statsd - # A namespace to prepend to all statsd calls. + + DEFAULT_HOST = '127.0.0.1' + DEFAULT_PORT = 8125 + + # A namespace to prepend to all statsd calls. Defaults to no namespace. attr_reader :namespace # StatsD host. Defaults to 127.0.0.1. - attr_accessor :host + attr_reader :host # StatsD port. Defaults to 8125. - attr_accessor :port + attr_reader :port + # Global tags to be added to every statsd call. Defaults to no tags. + attr_reader :tags + class << self # Set to a standard logger instance to enable debug logging. attr_accessor :logger end # Return the current version of the library. def self.VERSION - "1.1.0" + "1.2.0" end # @param [String] host your statsd host # @param [Integer] port your statsd port - def initialize(host = '127.0.0.1', port = 8125) + # @option opts [String] :namespace set a namespace to be prepended to every metric name + # @option opts [Array<String>] :tags tags to be added to every metric + def initialize(host = DEFAULT_HOST, port = DEFAULT_PORT, opts = {}) self.host, self.port = host, port @prefix = nil @socket = UDPSocket.new + self.namespace = opts[:namespace] + self.tags = opts[:tags] end def namespace=(namespace) #:nodoc: @namespace = namespace - @prefix = "#{namespace}." + @prefix = namespace.nil? ? nil : "#{namespace}." end def host=(host) #:nodoc: @host = host || '127.0.0.1' end def port=(port) #:nodoc: @port = port || 8125 end + def tags=(tags) #:nodoc: + @tags = tags || [] + end + # Sends an increment (count = 1) for the given stat to the statsd server. # # @param [String] stat stat name # @param [Hash] opts the options to create the metric with # @option opts [Numeric] :sample_rate sample rate, 1 for always @@ -167,10 +184,11 @@ sample_rate = opts[:sample_rate] || 1 if sample_rate == 1 or rand < sample_rate # Replace Ruby module scoping with '.' and reserved chars (: | @) with underscores. stat = stat.to_s.gsub('::', '.').tr(':|@', '_') rate = "|@#{sample_rate}" unless sample_rate == 1 - tags = "|##{opts[:tags].join(",")}" if opts[:tags] + ts = (tags || []) + (opts[:tags] || []) + tags = "|##{ts.join(",")}" unless ts.empty? send_to_socket "#{@prefix}#{stat}:#{delta}|#{type}#{rate}#{tags}" end end def send_to_socket(message)