micro_kit/
metrics.rs

1pub use metrics_lib::metrics::{Metric, Counter, StdCounter};
2
3use std::collections::HashMap;
4
5use ::json;
6
7use ::iron::prelude::{IronResult, Response};
8use ::iron::status;
9
10pub struct MetricsService {
11
12    metrics: HashMap<String, Metric>,
13    reporter_name: String,
14
15}
16
17impl MetricsService {
18
19    pub fn get_name(&self) -> &str {
20        &(*self.reporter_name)
21    }
22
23    pub fn add<S: Into<String>>(&mut self, name: S, metric: Metric) -> Result<(), String> {
24        let n = name.into();
25        match self.metrics.insert(n.clone(), metric) {
26            Some(_) => Ok(()),
27            None => Err(format!("Unable to attach metric reporter {}, {:?}", n, self.metrics.len())),
28        }
29    }
30
31    pub fn new<S: Into<String>>(reporter_name: S) -> Self {
32        MetricsService {
33            metrics: HashMap::new(),
34            reporter_name: reporter_name.into(),
35        }
36    }
37
38    pub fn report(&self) -> IronResult<Response> {
39        let mut report: HashMap<&String,i64> = HashMap::new();
40        for (name, metric) in &self.metrics {
41            let snapshot = match *metric {
42                Metric::Meter(ref x) => {
43                    x.snapshot().count as i64
44                }
45                Metric::Gauge(ref x ) => {
46                    x.snapshot().value as i64
47                }
48                Metric::Counter(ref x) => {
49                    x.snapshot().value as i64
50                }
51                Metric::Histogram(_) => {
52                   -1 as i64
53                }
54            };
55            report.insert(name, snapshot);
56        }
57        match json::to_string(&report) {
58            Ok(r) => {
59                Ok(Response::with((status::Ok, r)))
60            },
61            Err(e) => Ok(Response::with((status::InternalServerError, format!("{:?}", e))))
62        }
63
64    }
65}