MetricBuilder

Struct MetricBuilder 

Source
pub struct MetricBuilder<'m, 'c, T>
where T: Metric + From<String>,
{ /* private fields */ }
Expand description

Builder for adding tags to in-progress metrics.

This builder adds tags, key-value pairs or just values, to a metric that was previously constructed by a call to a method on StatsdClient. The tags are added to metrics and sent via the client when MetricBuilder::send() or MetricBuilder::try_send()is invoked. Any errors encountered constructing, validating, or sending the metrics will be propagated and returned when those methods are finally invoked.

Currently, only Datadog style tags are supported. For more information on the exact format used, see the Datadog docs.

Adding tags to a metric via this builder will typically result in one or more extra heap allocations.

NOTE: The only way to instantiate an instance of this builder is via methods in in the StatsdClient client.

§Examples

§.try_send()

An example of how the metric builder is used with a StatsdClient instance is given below.

use cadence::prelude::*;
use cadence::{StatsdClient, NopMetricSink, Metric};

let client = StatsdClient::from_sink("some.prefix", NopMetricSink);
let res = client.count_with_tags("some.key", 1)
   .with_tag("host", "app11.example.com")
   .with_tag("segment", "23")
   .with_tag_value("beta")
   .try_send();

assert_eq!(
    concat!(
        "some.prefix.some.key:1|c|#",
        "host:app11.example.com,",
        "segment:23,",
        "beta"
    ),
    res.unwrap().as_metric_str()
);

In this example, two key-value tags and one value tag are added to the metric before it is finally sent to the Statsd server.

§.send()

An example of how the metric builder is used with a StatsdClient instance when using the “quiet” method is given below.

use cadence::prelude::*;
use cadence::{StatsdClient, NopMetricSink, Metric};

let client = StatsdClient::builder("some.prefix", NopMetricSink)
    .with_error_handler(|e| eprintln!("metric error: {}", e))
    .build();
client.count_with_tags("some.key", 1)
   .with_tag("host", "app11.example.com")
   .with_tag("segment", "23")
   .with_tag_value("beta")
   .send();

Note that nothing is returned from the .send() method. Any errors encountered in this case will be passed to the error handler we registered.

Implementations§

Source§

impl<'m, 'c, T> MetricBuilder<'m, 'c, T>
where T: Metric + From<String>,

Source

pub fn with_tag(self, key: &'m str, value: &'m str) -> Self

Add a key-value tag to this metric.

§Example
use cadence::prelude::*;
use cadence::{StatsdClient, NopMetricSink, Metric};

let client = StatsdClient::from_sink("some.prefix", NopMetricSink);
let res = client.count_with_tags("some.key", 1)
   .with_tag("user", "authenticated")
   .try_send();

assert_eq!(
   "some.prefix.some.key:1|c|#user:authenticated",
   res.unwrap().as_metric_str()
);
Examples found in repository?
examples/value-packing.rs (line 31)
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}
More examples
Hide additional examples
examples/sending-tags.rs (line 35)
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 with_tag_value(self, value: &'m str) -> Self

Add a value tag to this metric.

§Example
use cadence::prelude::*;
use cadence::{StatsdClient, NopMetricSink, Metric};

let client = StatsdClient::from_sink("some.prefix", NopMetricSink);
let res = client.count_with_tags("some.key", 4)
   .with_tag_value("beta-testing")
   .try_send();

assert_eq!(
   "some.prefix.some.key:4|c|#beta-testing",
   res.unwrap().as_metric_str()
);
Source

pub fn with_container_id(self, container_id: &'m str) -> Self

Add a container_id to this metric.

Examples found in repository?
examples/datadog-extensions.rs (line 33)
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}
Source

pub fn with_timestamp(self, timestamp: u64) -> Self

Add a UNIX timestamp in seconds to this metric.

§Example
use cadence::prelude::*;
use cadence::{StatsdClient, NopMetricSink, Metric};
use std::time::{SystemTime, UNIX_EPOCH};

let client = StatsdClient::from_sink("some.prefix", NopMetricSink);
let timestamp = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs();
let res = client.count_with_tags("some.key", 1)
  .with_timestamp(timestamp)
  .try_send();

assert_eq!(
  "some.prefix.some.key:1|c|T".to_string() + &timestamp.to_string(),
 res.unwrap().as_metric_str()
);
Examples found in repository?
examples/datadog-extensions.rs (line 32)
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}
Source

pub fn with_sampling_rate(self, rate: f64) -> Self

Add a sampling rate to this metric.

The sampling rate is a float between 0 and 1 that determines the rate at which the metric is sampled. For example, a sampling rate of 0.5 would mean that the metric is sent 50% of the time. The sampling has to be done by the caller, cadence will simply forward it to the backend.

§Example
use cadence::prelude::*;
use cadence::{StatsdClient, NopMetricSink, Metric};

let client = StatsdClient::from_sink("some.prefix", NopMetricSink);
let res = client.distribution_with_tags("some.key", 1)
 .with_sampling_rate(0.5)
 .try_send();

assert_eq!(
 "some.prefix.some.key:1|d|@0.5",
 res.unwrap().as_metric_str()
);
Examples found in repository?
examples/datadog-extensions.rs (line 34)
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}
Source

pub fn try_send(self) -> MetricResult<T>

Send a metric using the client that created this builder.

Note that the builder is consumed by this method and thus .try_send() can only be called a single time per builder.

§Example
use cadence::prelude::*;
use cadence::{StatsdClient, NopMetricSink, Metric};

let client = StatsdClient::from_sink("some.prefix", NopMetricSink);
let res = client.gauge_with_tags("some.key", 7)
   .with_tag("test-segment", "12345")
   .try_send();

assert_eq!(
   "some.prefix.some.key:7|g|#test-segment:12345",
   res.unwrap().as_metric_str()
);
Examples found in repository?
examples/datadog-extensions.rs (line 39)
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 42)
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 46)
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 send(self)

Send a metric using the client that created this builder, discarding successful results and invoking a custom handler for error results.

By default, if no handler is given, a “no-op” handler is used that simply discards all errors. If this isn’t desired, a custom handler should be supplied when creating a new StatsdClient instance.

Note that the builder is consumed by this method and thus .send() can only be called a single time per builder.

§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 35)
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 33)
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 37)
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}

Trait Implementations§

Source§

impl<'m, 'c, T> Debug for MetricBuilder<'m, 'c, T>
where T: Metric + From<String> + Debug,

Source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<'m, 'c, T> Freeze for MetricBuilder<'m, 'c, T>

§

impl<'m, 'c, T> !RefUnwindSafe for MetricBuilder<'m, 'c, T>

§

impl<'m, 'c, T> Send for MetricBuilder<'m, 'c, T>
where T: Send,

§

impl<'m, 'c, T> Sync for MetricBuilder<'m, 'c, T>
where T: Sync,

§

impl<'m, 'c, T> Unpin for MetricBuilder<'m, 'c, T>
where T: Unpin,

§

impl<'m, 'c, T> !UnwindSafe for MetricBuilder<'m, 'c, T>

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.