API Reference
The StatsClient
provides accessors for all the types of data the statsd
server supports.
Note
Each public stats API method supports a rate
parameter, but statsd
doesn’t always use it the same way. See the Data Types for more
information.
- class StatsClient(host='localhost', port=8125, prefix=None, maxudpsize=512)
Create a new
StatsClient
instance with the appropriate connection and prefix information.- Parameters
host (str) – the hostname or IP address of the statsd server
port (int) – the port of the statsd server
prefix (str or None) – a prefix to distinguish and group stats from an application or environment
maxudpsize (int) – the largest safe UDP packet to send. 512 is generally considered safe for the public internet, but private networks may support larger packet sizes.
- StatsClient.close()
Close the underlying UDP socket.
- StatsClient.incr(stat, count=1, rate=1)
Increment a counter.
- Parameters
stat (str) – the name of the counter to increment
count (int) – the amount to increment by. Typically an integer. May be negative, but see also
decr()
.rate (float) – a sample rate, a float between 0 and 1. Will only send data this percentage of the time. The statsd server will take the sample rate into account for counters.
- StatsClient.decr(stat, count=1, rate=1)
Decrement a counter.
- Parameters
stat (str) – the name of the counter to increment
count (int) – the amount to increment by. Typically an integer. May be negative, but that will have the impact of incrementing the counter but see also
incr()
.rate (float) – a sample rate, a float between 0 and 1. Will only send data this percentage of the time. The statsd server will take the sample rate into account for counters
- StatsClient.gauge(stat, value, rate=1, delta=False)
Set a gauge value.
- Parameters
stat (str) – the name of the gauge to set
value (int or float) – the current value of the gauge
rate (float) – a sample rate, a float between 0 and 1. Will only send data this percentage of the time. The statsd server does not take the sample rate into account for gauges. Use with care
delta (bool) – whether or not to consider this a delta value or an absolute value. See the gauge type for more detail
Note
Gauges were added to the statsd server in version 0.1.1.
Note
Gauge deltas were added to the statsd server in version 0.6.0.
- StatsClient.set(stat, value, rate=1)
Increment a set value.
- Parameters
stat (str) – the name of the set to update
value – the unique value to count
rate (float) – a sample rate, a float between 0 and 1. Will only send data this percentage of the time. The statsd server does not take the sample rate into account for sets. Use with care.
Note
Sets were added to the statsd server in version 0.6.0.
- StatsClient.timing(stat, delta, rate=1)
Record timer information.
- Parameters
stat (str) – the name of the timer to use
delta (int or float or datetime.timedelta) – the number of milliseconds whatever action took.
datetime.timedelta
objects will be converted to millisecondsrate (float) – a sample rate, a float between 0 and 1. Will only send data this percentage of the time. The statsd server does not take the sample rate into account for timers.
- StatsClient.timer(stat, rate=1)
Return a
Timer
object that can be used as a context manager or decorator to automatically record timing for a block or function call. See also the chapter on timing.- Parameters
stat (str) – the name of the timer to use
rate (float) – a sample rate, a float between 0 and 1. Will only send data this percentage of the time. The statsd server does not take the sample rate into account for timers.
with StatsClient().timer(stat, rate=1):
pass
# or
@StatsClient().timer(stat, rate=1)
def foo():
pass
# or (see below for more Timer methods)
timer = StatsClient().timer('foo', rate=1)
with timer:
pass
@timer
def bar():
pass
- StatsClient.pipeline()
Returns a
Pipeline
object for collecting several stats. Can also be used as a context manager.
pipe = StatsClient().pipeline()
pipe.incr('foo')
pipe.send()
# or
with StatsClient().pipeline as pipe:
pipe.incr('bar')
- class Timer
The Timer objects returned by
StatsClient.timer()
. These should never be instantiated directly.
Timer
objects should not be shared between threads (except when
used as decorators, which is thread-safe) but could be used within another
context manager or decorator. For example:
@contextmanager
def my_context():
timer = statsd.timer('my_context_timer')
timer.start()
try:
yield
finally:
timer.stop()
Timer
objects may be reused by calling start()
again.
- Timer.start()
Causes a timer object to start counting. Called automatically when the object is used as a decorator or context manager. Returns the timer object for simplicity.
- Timer.stop(send=True)
Causes the timer object to stop timing and send the results to statsd. Can be called with
send=False
to prevent immediate sending immediately, and usesend()
. Called automatically when the object is used as a decorator or context manager. Returns the timer object.If
stop()
is called beforestart()
, aRuntimeError
is raised.- Parameters
send (bool) – Whether to automatically send the results
timer = StatsClient().timer('foo').start()
timer.stop()
- Timer.send()
Causes the timer to send any unsent data. If the data has already been sent, or has not yet been recorded, a
RuntimeError
is raised.
timer = StatsClient().timer('foo').start()
timer.stop(send=False)
timer.send()
Note
See the note abbout timer objects and pipelines.
- class Pipeline
A Pipeline object that can be used to collect and send several stats at once. Useful for reducing network traffic and speeding up instrumentation under certain loads. Can be used as a context manager.
Pipeline extends
StatsClient
and has all associated methods.
pipe = StatsClient().pipeline()
pipe.incr('foo')
pipe.send()
# or
with StatsClient().pipeline as pipe:
pipe.incr('bar')
- Pipeline.send()
Causes the
Pipeline
object to send all batched stats in as few packets as possible.
- class TCPStatsClient(host='localhost', port=8125, prefix=None, timeout=None, ipv6=False)
Create a new
TCPStatsClient
instance with the appropriate connection and prefix information.- Parameters
host (str) – the hostname or IP address of the statsd server
port (int) – the port of the statsd server
prefix (str or None) – a prefix to distinguish and group stats from an application or environment.
timeout (float) – socket timeout for any actions on the connection socket.
TCPStatsClient
implements all methods of StatsClient
, including
pipeline()
, with the difference that it is
not thread safe and it can raise exceptions on connection errors. Unlike
StatsClient
it uses a TCP connection to communicate with StatsD.
In addition to the stats methods, TCPStatsClient
supports the following
TCP-specific methods.
- TCPStatsClient.close()
Closes a connection that’s currently open and deletes it’s socket. If this is called on a
TCPStatsClient
which currently has no open connection it is a non-action.
from statsd import TCPStatsClient
statsd = TCPStatsClient()
statsd.incr('some.event')
statsd.close()
- TCPStatsClient.connect()
Creates a connection to StatsD. If there are errors like connection timed out or connection refused, the according exceptions will be raised. It is usually not necessary to call this method because sending data to StatsD will call
connect
implicitely if the current instance ofTCPStatsClient
does not already hold an open connection.
from statsd import TCPStatsClient
statsd = TCPStatsClient()
statsd.incr('some.event') # calls connect() internally
statsd.close()
statsd.connect() # creates new connection
- TCPStatsClient.reconnect()
Closes a currently existing connection and replaces it with a new one. If no connection exists already it will simply create a new one. Internally this does nothing else than calling
close()
andconnect()
.
from statsd import TCPStatsClient
statsd = TCPStatsClient()
statsd.incr('some.event')
statsd.reconnect() # closes open connection and creates new one
- class UnixSocketStatsClient(socket_path, prefix=None, timeout=None)
A version of
StatsClient
that communicates over Unix sockets. It implements all methods ofStatsClient
.- Parameters
socket_path (str) – the path to the (writeable) Unix socket
prefix (str or None) – a prefix to distinguish and group stats from an application or environment
timeout (float) – socket timeout for any actions on the connection socket.