quickwit_common/
metrics.rs

1// Copyright (C) 2021 Quickwit, Inc.
2//
3// Quickwit is offered under the AGPL v3.0 and as commercial software.
4// For commercial licensing, contact us at hello@quickwit.io.
5//
6// AGPL:
7// This program is free software: you can redistribute it and/or modify
8// it under the terms of the GNU Affero General Public License as
9// published by the Free Software Foundation, either version 3 of the
10// License, or (at your option) any later version.
11//
12// This program is distributed in the hope that it will be useful,
13// but WITHOUT ANY WARRANTY; without even the implied warranty of
14// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15// GNU Affero General Public License for more details.
16//
17// You should have received a copy of the GNU Affero General Public License
18// along with this program. If not, see <http://www.gnu.org/licenses/>.
19
20use prometheus::{Encoder, IntCounter, IntGauge, Opts, TextEncoder};
21
22pub fn new_counter(name: &str, description: &str) -> IntCounter {
23    let counter =
24        IntCounter::with_opts(Opts::new(name, description)).expect("Failed to create counter");
25    prometheus::register(Box::new(counter.clone())).expect("Failed to register counter");
26    counter
27}
28
29pub fn new_gauge(name: &str, description: &str) -> IntGauge {
30    let gauge = IntGauge::with_opts(Opts::new(name, description)).expect("Failed to create gauge");
31    prometheus::register(Box::new(gauge.clone())).expect("Failed to register gauge");
32    gauge
33}
34
35pub fn metrics_handler() -> impl warp::Reply {
36    let metric_families = prometheus::gather();
37    let mut buffer = Vec::new();
38    let encoder = TextEncoder::new();
39    let _ = encoder.encode(&metric_families, &mut buffer); // TODO avoid ignoring the error.
40    String::from_utf8_lossy(&buffer).to_string()
41}