Struct 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.

  • Counted for emitting counters.
  • Timed for emitting timings.
  • Gauged for emitting gauge values.
  • Metered for emitting meter values.
  • Histogrammed for emitting histogram values.
  • Distributed for emitting distribution values.
  • Setted for emitting set values.
  • MetricClient for 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§

Source§

impl StatsdClient

Source

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);
Examples found in repository?
examples/arc-wrapped-client.rs (line 30)
28    fn new() -> ThreadedHandler {
29        ThreadedHandler {
30            metrics: Arc::new(StatsdClient::from_sink("example.prefix", NopMetricSink)),
31        }
32    }
More examples
Hide additional examples
examples/custom-value-type.rs (line 37)
35fn main() {
36    let sink = NopMetricSink;
37    let client = StatsdClient::from_sink("example.prefix", sink);
38
39    client.gauge("user.happiness", UserHappiness::VeryHappy).unwrap();
40    client.gauge("user.happiness", UserHappiness::KindaHappy).unwrap();
41    client.gauge("user.happiness", UserHappiness::Sad).unwrap();
42}
examples/nop-sink.rs (line 20)
18fn main() {
19    let sink = NopMetricSink;
20    let client = StatsdClient::from_sink("example.prefix", sink);
21
22    client.count("example.counter", 1).unwrap();
23    client.gauge("example.gauge", 5).unwrap();
24    client.gauge("example.gauge", 5.0).unwrap();
25    client.time("example.timer", 32).unwrap();
26    client.time("example.timer", Duration::from_millis(32)).unwrap();
27    client.histogram("example.histogram", 22).unwrap();
28    client.histogram("example.histogram", Duration::from_nanos(22)).unwrap();
29    client.histogram("example.histogram", 22.0).unwrap();
30    client.distribution("example.distribution", 33).unwrap();
31    client.distribution("example.distribution", 33.0).unwrap();
32    client.meter("example.meter", 8).unwrap();
33    client.set("example.set", 44).unwrap();
34}
examples/simple-sink.rs (line 22)
19fn main() {
20    let sock = UdpSocket::bind("0.0.0.0:0").unwrap();
21    let sink = UdpMetricSink::from(("localhost", DEFAULT_PORT), sock).unwrap();
22    let client = StatsdClient::from_sink("example.prefix", sink);
23
24    client.count("example.counter", 1).unwrap();
25    client.gauge("example.gauge", 5).unwrap();
26    client.gauge("example.gauge", 5.0).unwrap();
27    client.time("example.timer", 32).unwrap();
28    client.time("example.timer", Duration::from_millis(32)).unwrap();
29    client.histogram("example.histogram", 22).unwrap();
30    client.histogram("example.histogram", Duration::from_nanos(22)).unwrap();
31    client.histogram("example.histogram", 22.0).unwrap();
32    client.distribution("example.distribution", 33).unwrap();
33    client.distribution("example.distribution", 33.0).unwrap();
34    client.meter("example.meter", 8).unwrap();
35    client.set("example.set", 44).unwrap();
36}
examples/wrapped.rs (line 54)
50fn main() {
51    let real_sink = NopMetricSink;
52    let reference1 = CloneableSink::new(real_sink);
53    let reference2 = reference1.clone();
54    let client = StatsdClient::from_sink("prefix", reference1);
55
56    let _ = reference2.flush();
57
58    client.count("example.counter", 1).unwrap();
59    client.gauge("example.gauge", 5).unwrap();
60    client.gauge("example.gauge", 5.0).unwrap();
61    client.time("example.timer", 32).unwrap();
62    client.time("example.timer", Duration::from_millis(32)).unwrap();
63    client.histogram("example.histogram", 22).unwrap();
64    client.histogram("example.histogram", Duration::from_nanos(22)).unwrap();
65    client.histogram("example.histogram", 22.0).unwrap();
66    client.distribution("example.distribution", 33).unwrap();
67    client.distribution("example.distribution", 33.0).unwrap();
68    client.meter("example.meter", 8).unwrap();
69    client.set("example.set", 44).unwrap();
70
71    let _ = reference2.flush();
72}
examples/production-sink.rs (line 24)
20fn main() {
21    let sock = UdpSocket::bind("0.0.0.0:0").unwrap();
22    let buffered = BufferedUdpMetricSink::from(("localhost", DEFAULT_PORT), sock).unwrap();
23    let queued = QueuingMetricSink::from(buffered);
24    let client = StatsdClient::from_sink("example.prefix", queued);
25
26    client.count("example.counter", 1).unwrap();
27    client.gauge("example.gauge", 5).unwrap();
28    client.gauge("example.gauge", 5.0).unwrap();
29    client.time("example.timer", 32).unwrap();
30    client.time("example.timer", Duration::from_millis(32)).unwrap();
31    client.histogram("example.histogram", 22).unwrap();
32    client.histogram("example.histogram", Duration::from_nanos(22)).unwrap();
33    client.histogram("example.histogram", 22.0).unwrap();
34    client.distribution("example.distribution", 33).unwrap();
35    client.distribution("example.distribution", 33.0).unwrap();
36    client.meter("example.meter", 8).unwrap();
37    client.set("example.set", 44).unwrap();
38}
Source

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();
Examples found in repository?
examples/datadog-extensions.rs (line 22)
16fn main() {
17    fn my_error_handler(err: MetricError) {
18        eprintln!("Error sending metrics: {}", err);
19    }
20
21    // Create a client with an error handler and default "region" tag
22    let client = StatsdClient::builder("my.prefix", NopMetricSink)
23        .with_error_handler(my_error_handler)
24        .with_container_id("container-123")
25        .build();
26
27    // In this case we are sending a counter metric with manually set timestamp,
28    // container id and sampling rate. If sending the metric fails, our error
29    // handler set above will be invoked to do something with the metric error.
30    client
31        .count_with_tags("counter.1", 1)
32        .with_timestamp(123456)
33        .with_container_id("container-456")
34        .with_sampling_rate(0.5)
35        .send();
36
37    // In this case we are sending the same counter metrics without any explicit container
38    // id, meaning that the client's container id will be used.
39    let res = client.count_with_tags("counter.2", 1).try_send();
40
41    println!("Result of metric send: {:?}", res);
42}
More examples
Hide additional examples
examples/value-packing.rs (line 22)
17fn main() {
18    fn my_error_handler(err: MetricError) {
19        eprintln!("Error sending metrics: {}", err);
20    }
21
22    let client = StatsdClient::builder("my.prefix", NopMetricSink)
23        .with_error_handler(my_error_handler)
24        .build();
25
26    // In this case we are sending a distribution metric with two tag key-value
27    // pairs. If sending the metric fails, our error handler set above will
28    // be invoked to do something with the metric error.
29    client
30        .distribution_with_tags("latency.milliseconds", vec![10, 20, 30, 40, 50])
31        .with_tag("app", "search")
32        .with_tag("region", "us-west-2")
33        .send();
34
35    // In this case we are sending the same distribution metrics with two tags.
36    // The results of sending the metric (or failing to send it) are returned
37    // to the caller to do something with.
38    let res = client
39        .distribution_with_tags("latency.milliseconds", vec![10, 20, 30, 40, 50])
40        .with_tag("app", "search")
41        .with_tag("region", "us-west-2")
42        .try_send();
43
44    println!("Result of metric send: {:?}", res);
45}
examples/sending-tags.rs (line 25)
19fn main() {
20    fn my_error_handler(err: MetricError) {
21        eprintln!("Error sending metrics: {}", err);
22    }
23
24    // Create a client with an error handler and default "region" tag
25    let client = StatsdClient::builder("my.prefix", NopMetricSink)
26        .with_error_handler(my_error_handler)
27        .with_tag("region", "us-west-2")
28        .build();
29
30    // In this case we are sending a counter metric with two tag key-value
31    // pairs. If sending the metric fails, our error handler set above will
32    // be invoked to do something with the metric error.
33    client
34        .count_with_tags("requests.handled", 1)
35        .with_tag("app", "search")
36        .with_tag("user", "1234")
37        .send();
38
39    // In this case we are sending the same counter metrics with two tags.
40    // The results of sending the metric (or failing to send it) are returned
41    // to the caller to do something with.
42    let res = client
43        .count_with_tags("requests.handled", 1)
44        .with_tag("app", "search")
45        .with_tag("user", "1234")
46        .try_send();
47
48    println!("Result of metric send: {:?}", res);
49}
Source

pub fn flush(&self) -> MetricResult<()>

Flush the underlying metric sink.

This is helpful for when you’d like to buffer metrics but still want strong control over when to emit them. For example, you are using a BufferedUdpMetricSink and have just emitted some time-sensitive metrics, but you aren’t sure if the buffer is full or not. Thus, you can use flush to force the sink to flush your metrics now.

§Buffered UDP Socket Example
use std::net::UdpSocket;
use cadence::prelude::*;
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);

client.count("time-sensitive.keyA", 1);
client.count("time-sensitive.keyB", 2);
client.count("time-sensitive.keyC", 3);
// Any number of time-sensitive metrics ...
client.flush();

Trait Implementations§

Source§

impl<T> Counted<T> for StatsdClient
where T: ToCounterValue,

Source§

fn count_with_tags<'a>( &'a self, key: &'a str, value: T, ) -> MetricBuilder<'_, '_, Counter>

Increment or decrement the counter by the given amount and return a MetricBuilder that can be used to add tags to the metric.
Source§

fn count(&self, key: &str, count: T) -> MetricResult<Counter>

Increment or decrement the counter by the given amount
Source§

impl CountedExt for StatsdClient

Source§

fn incr(&self, key: &str) -> MetricResult<Counter>

Increment the counter by 1
Source§

fn incr_with_tags<'a>(&'a self, key: &'a str) -> MetricBuilder<'_, '_, Counter>

Increment the counter by 1 and return a MetricBuilder that can be used to add tags to the metric.
Source§

fn decr(&self, key: &str) -> MetricResult<Counter>

Decrement the counter by 1
Source§

fn decr_with_tags<'a>(&'a self, key: &'a str) -> MetricBuilder<'_, '_, Counter>

Decrement the counter by 1 and return a MetricBuilder that can be used to add tags to the metric.
Source§

impl Debug for StatsdClient

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<T> Distributed<T> for StatsdClient

Source§

fn distribution_with_tags<'a>( &'a self, key: &'a str, value: T, ) -> MetricBuilder<'_, '_, Distribution>

Record a single distribution value with the given key and return a MetricBuilder that can be used to add tags to the metric.
Source§

fn distribution(&self, key: &str, value: T) -> MetricResult<Distribution>

Record a single distribution value with the given key
Source§

impl<T> Gauged<T> for StatsdClient
where T: ToGaugeValue,

Source§

fn gauge_with_tags<'a>( &'a self, key: &'a str, value: T, ) -> MetricBuilder<'_, '_, Gauge>

Record a gauge value with the given key and return a MetricBuilder that can be used to add tags to the metric.
Source§

fn gauge(&self, key: &str, value: T) -> MetricResult<Gauge>

Record a gauge value with the given key
Source§

impl<T> Histogrammed<T> for StatsdClient

Source§

fn histogram_with_tags<'a>( &'a self, key: &'a str, value: T, ) -> MetricBuilder<'_, '_, Histogram>

Record a single histogram value with the given key and return a MetricBuilder that can be used to add tags to the metric.
Source§

fn histogram(&self, key: &str, value: T) -> MetricResult<Histogram>

Record a single histogram value with the given key
Source§

impl<T> Metered<T> for StatsdClient
where T: ToMeterValue,

Source§

fn meter_with_tags<'a>( &'a self, key: &'a str, value: T, ) -> MetricBuilder<'_, '_, Meter>

Record a meter value with the given key and return a MetricBuilder that can be used to add tags to the metric.
Source§

fn meter(&self, key: &str, value: T) -> MetricResult<Meter>

Record a meter value with the given key
Source§

impl MetricBackend for StatsdClient

Source§

fn send_metric<M>(&self, metric: &M) -> MetricResult<()>
where M: Metric,

Send a full formed Metric implementation via the underlying MetricSink Read more
Source§

fn consume_error(&self, err: MetricError)

Consume a possible error from attempting to send a metric. Read more
Source§

impl<T> Setted<T> for StatsdClient
where T: ToSetValue,

Source§

fn set_with_tags<'a>( &'a self, key: &'a str, value: T, ) -> MetricBuilder<'_, '_, Set>

Record a single set value with the given key and return a MetricBuilder that can be used to add tags to the metric.
Source§

fn set(&self, key: &str, value: T) -> MetricResult<Set>

Record a single set value with the given key
Source§

impl<T> Timed<T> for StatsdClient
where T: ToTimerValue,

Source§

fn time_with_tags<'a>( &'a self, key: &'a str, time: T, ) -> MetricBuilder<'_, '_, Timer>

Record a timing in milliseconds with the given key and return a MetricBuilder that can be used to add tags to the metric.
Source§

fn time(&self, key: &str, time: T) -> MetricResult<Timer>

Record a timing in milliseconds with the given key
Source§

impl MetricClient for StatsdClient

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.