Struct cadence::StatsdClient
source · [−]pub struct StatsdClient { /* private fields */ }Expand description
Client for Statsd that implements various traits to record metrics.
Traits
The client is the main entry point for users of this library. It supports several traits for recording metrics of different types.
Countedfor emitting counters.Timedfor emitting timings.Gaugedfor emitting gauge values.Meteredfor emitting meter values.Histogrammedfor emitting histogram values.Distributedfor emitting distribution values.Settedfor emitting set values.MetricClientfor a combination of all of the above.
For more information about the uses for each type of metric, see the documentation for each mentioned trait.
Sinks
The client uses some implementation of a MetricSink to emit the metrics.
In simple use cases when performance isn’t critical, the UdpMetricSink
is an acceptable choice since it is the simplest to use and understand.
When performance is more important, users will want to use the
BufferedUdpMetricSink in combination with the QueuingMetricSink for
maximum isolation between the sending of metrics and your application as well
as minimum overhead when sending metrics.
Threading
The StatsdClient is designed to work in a multithreaded application. All
parts of the client can be shared between threads (i.e. it is Send and
Sync). An example of how to use the client in a multithreaded environment
is given below.
In the following example, we create a struct MyRequestHandler that has a
single method that spawns a thread to do some work and emit a metric.
Wrapping With An Arc
In order to share a client between multiple threads, you’ll need to wrap it
with an atomic reference counting pointer (std::sync::Arc). You should refer
to the client by the trait of all its methods for recording metrics
(MetricClient) as well as the Send and Sync traits since the idea is to
share this between threads.
use std::panic::RefUnwindSafe;
use std::net::UdpSocket;
use std::sync::Arc;
use std::thread;
use cadence::prelude::*;
use cadence::{StatsdClient, BufferedUdpMetricSink, DEFAULT_PORT};
struct MyRequestHandler {
metrics: Arc<dyn MetricClient + Send + Sync + RefUnwindSafe>,
}
impl MyRequestHandler {
fn new() -> MyRequestHandler {
let socket = UdpSocket::bind("0.0.0.0:0").unwrap();
let host = ("localhost", DEFAULT_PORT);
let sink = BufferedUdpMetricSink::from(host, socket).unwrap();
MyRequestHandler {
metrics: Arc::new(StatsdClient::from_sink("some.prefix", sink))
}
}
fn handle_some_request(&self) -> Result<(), String> {
let metric_ref = self.metrics.clone();
let _t = thread::spawn(move || {
println!("Hello from the thread!");
metric_ref.count("request.handler", 1);
});
Ok(())
}
}Implementations
sourceimpl StatsdClient
impl StatsdClient
sourcepub fn from_sink<T>(prefix: &str, sink: T) -> Self where
T: MetricSink + Sync + Send + RefUnwindSafe + 'static,
pub fn from_sink<T>(prefix: &str, sink: T) -> Self where
T: MetricSink + Sync + Send + RefUnwindSafe + 'static,
Create a new client instance that will use the given prefix for
all metrics emitted to the given MetricSink implementation.
Note that this client will discard errors encountered when
sending metrics via the MetricBuilder::send() method.
No-op Example
use cadence::{StatsdClient, NopMetricSink};
let prefix = "my.stats";
let client = StatsdClient::from_sink(prefix, NopMetricSink);UDP Socket Example
use std::net::UdpSocket;
use cadence::{StatsdClient, UdpMetricSink, DEFAULT_PORT};
let prefix = "my.stats";
let host = ("127.0.0.1", DEFAULT_PORT);
let socket = UdpSocket::bind("0.0.0.0:0").unwrap();
socket.set_nonblocking(true).unwrap();
let sink = UdpMetricSink::from(host, socket).unwrap();
let client = StatsdClient::from_sink(prefix, sink);Buffered UDP Socket Example
use std::net::UdpSocket;
use cadence::{StatsdClient, BufferedUdpMetricSink, DEFAULT_PORT};
let prefix = "my.stats";
let host = ("127.0.0.1", DEFAULT_PORT);
let socket = UdpSocket::bind("0.0.0.0:0").unwrap();
let sink = BufferedUdpMetricSink::from(host, socket).unwrap();
let client = StatsdClient::from_sink(prefix, sink);sourcepub fn from_udp_host<A>(prefix: &str, host: A) -> MetricResult<Self> where
A: ToSocketAddrs,
👎 Deprecated since 0.19.0: Superseded by ::from_sink() and ::builder()
pub fn from_udp_host<A>(prefix: &str, host: A) -> MetricResult<Self> where
A: ToSocketAddrs,
Superseded by ::from_sink() and ::builder()
Create a new client instance that will use the given prefix to send metrics to the given host over UDP using an appropriate sink.
The created UDP socket will be put into non-blocking mode.
Note that this client will discard errors encountered when
sending metrics via the MetricBuilder::send() method.
Example
use cadence::{StatsdClient, UdpMetricSink};
let prefix = "my.stats";
let host = ("metrics.example.com", 8125);
let client = StatsdClient::from_udp_host(prefix, host);Failures
This method may fail if:
- It is unable to create a local UDP socket.
- It is unable to put the UDP socket into non-blocking mode.
- It is unable to resolve the hostname of the metric server.
- The host address is otherwise unable to be parsed.
sourcepub fn builder<T>(prefix: &str, sink: T) -> StatsdClientBuilder where
T: MetricSink + Sync + Send + RefUnwindSafe + 'static,
pub fn builder<T>(prefix: &str, sink: T) -> StatsdClientBuilder where
T: MetricSink + Sync + Send + RefUnwindSafe + 'static,
Create a new builder with the provided prefix and metric sink.
A prefix and a metric sink are required to create a new client instance. All other optional customizations can be set by calling methods on the returned builder. Any customizations that aren’t set by the caller will use defaults.
Note, though a metric prefix is required, you may pass an empty string as a prefix. In this case, the metrics emitted will use only the bare keys supplied when you call the various methods to emit metrics.
General defaults:
- A no-op error handler will be used by default. Note that this
only affects errors encountered when using the
MetricBuilder::send()method (as opposed to.try_send()or any other method for sending metrics).
Example
use cadence::prelude::*;
use cadence::{StatsdClient, MetricError, NopMetricSink};
fn my_handler(err: MetricError) {
println!("Metric error: {}", err);
}
let client = StatsdClient::builder("some.prefix", NopMetricSink)
.with_error_handler(my_handler)
.build();
client.gauge_with_tags("some.key", 7)
.with_tag("region", "us-west-1")
.send();Trait Implementations
sourceimpl Compat for StatsdClient
impl Compat for StatsdClient
Use client.time_with_tags(key, val)
Use client.gauge_with_tags(key, val)
Use client.meter_with_tags(key, 1)
Use client.histogram_with_tags(key, val)
sourcefn time_duration(&self, key: &str, val: Duration) -> MetricResult<Timer>
fn time_duration(&self, key: &str, val: Duration) -> MetricResult<Timer>
Use client.time(key, val)
sourcefn gauge_f64(&self, key: &str, val: f64) -> MetricResult<Gauge>
fn gauge_f64(&self, key: &str, val: f64) -> MetricResult<Gauge>
Use client.gauge(key, val)
sourcefn mark(&self, key: &str) -> MetricResult<Meter>
fn mark(&self, key: &str) -> MetricResult<Meter>
Use client.meter(key, 1)
sourcefn histogram_duration(
&self,
key: &str,
val: Duration
) -> MetricResult<Histogram>
fn histogram_duration(
&self,
key: &str,
val: Duration
) -> MetricResult<Histogram>
Use client.histogram(key, val)
sourceimpl<T> Counted<T> for StatsdClient where
T: ToCounterValue,
impl<T> Counted<T> for StatsdClient where
T: ToCounterValue,
sourceimpl CountedExt for StatsdClient
impl CountedExt for StatsdClient
sourcefn incr(&self, key: &str) -> MetricResult<Counter>
fn incr(&self, key: &str) -> MetricResult<Counter>
Increment the counter by 1
Increment the counter by 1 and return a MetricBuilder that can
be used to add tags to the metric. Read more
sourcefn decr(&self, key: &str) -> MetricResult<Counter>
fn decr(&self, key: &str) -> MetricResult<Counter>
Decrement the counter by 1
Decrement the counter by 1 and return a MetricBuilder that can
be used to add tags to the metric. Read more
sourceimpl Debug for StatsdClient
impl Debug for StatsdClient
sourceimpl<T> Distributed<T> for StatsdClient where
T: ToDistributionValue,
impl<T> Distributed<T> for StatsdClient where
T: ToDistributionValue,
Record a single distribution value with the given key and return a
MetricBuilder that can be used to add tags to the metric. Read more
sourcefn distribution(&self, key: &str, value: T) -> MetricResult<Distribution>
fn distribution(&self, key: &str, value: T) -> MetricResult<Distribution>
Record a single distribution value with the given key
sourceimpl<T> Gauged<T> for StatsdClient where
T: ToGaugeValue,
impl<T> Gauged<T> for StatsdClient where
T: ToGaugeValue,
sourceimpl<T> Histogrammed<T> for StatsdClient where
T: ToHistogramValue,
impl<T> Histogrammed<T> for StatsdClient where
T: ToHistogramValue,
sourceimpl<T> Metered<T> for StatsdClient where
T: ToMeterValue,
impl<T> Metered<T> for StatsdClient where
T: ToMeterValue,
sourceimpl MetricBackend for StatsdClient
impl MetricBackend for StatsdClient
sourcefn send_metric<M>(&self, metric: &M) -> MetricResult<()> where
M: Metric,
fn send_metric<M>(&self, metric: &M) -> MetricResult<()> where
M: Metric,
Send a full formed Metric implementation via the underlying MetricSink Read more
sourcefn consume_error(&self, err: MetricError)
fn consume_error(&self, err: MetricError)
Consume a possible error from attempting to send a metric. Read more
sourceimpl<T> Setted<T> for StatsdClient where
T: ToSetValue,
impl<T> Setted<T> for StatsdClient where
T: ToSetValue,
sourceimpl<T> Timed<T> for StatsdClient where
T: ToTimerValue,
impl<T> Timed<T> for StatsdClient where
T: ToTimerValue,
impl MetricClient for StatsdClient
Auto Trait Implementations
impl RefUnwindSafe for StatsdClient
impl Send for StatsdClient
impl Sync for StatsdClient
impl Unpin for StatsdClient
impl !UnwindSafe for StatsdClient
Blanket Implementations
sourceimpl<T> BorrowMut<T> for T where
T: ?Sized,
impl<T> BorrowMut<T> for T where
T: ?Sized,
const: unstable · sourcefn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more