custom_value_type/
custom-value-type.rs

1// Cadence - An extensible Statsd client for Rust!
2//
3// To the extent possible under law, the author(s) have dedicated all copyright and
4// related and neighboring rights to this file to the public domain worldwide.
5// This software is distributed without any warranty.
6//
7// You should have received a copy of the CC0 Public Domain Dedication along with this
8// software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
9
10// This example shows how to use the various To*Value traits in Cadence to allow
11// custom types to be used as metric values.
12
13use cadence::ext::{MetricValue, ToGaugeValue};
14use cadence::prelude::*;
15use cadence::{MetricResult, NopMetricSink, StatsdClient};
16
17enum UserHappiness {
18    VeryHappy,
19    KindaHappy,
20    Sad,
21}
22
23impl ToGaugeValue for UserHappiness {
24    fn try_to_value(self) -> MetricResult<MetricValue> {
25        let v = match self {
26            UserHappiness::VeryHappy => 1.0,
27            UserHappiness::KindaHappy => 0.5,
28            UserHappiness::Sad => 0.0,
29        };
30
31        Ok(MetricValue::Float(v))
32    }
33}
34
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}