Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

src/encoding/text.rs: Expose Encoder methods #41

Merged
merged 3 commits into from
Feb 2, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,14 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [0.15.1] - [unreleased]

### Added

- Expose `Encoder` methods. See [PR 41].

[PR 41]: https://github.com/prometheus/client_rust/pull/41

## [0.15.0] - 2022-01-16

### Changed
Expand Down
5 changes: 3 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "prometheus-client"
version = "0.15.0"
version = "0.15.1"
authors = ["Max Inden <[email protected]>"]
edition = "2018"
description = "Open Metrics client library allowing users to natively instrument applications."
Expand All @@ -24,8 +24,9 @@ async-std = { version = "1", features = ["attributes"] }
criterion = "0.3"
http-types = "2"
pyo3 = "0.15"
tide = "0.16"
quickcheck = "1"
rand = "0.8.4"
tide = "0.16"

[[bench]]
name = "family"
Expand Down
52 changes: 52 additions & 0 deletions examples/custom-metric.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
use prometheus_client::encoding::text::{encode, EncodeMetric, Encoder};
use prometheus_client::metrics::MetricType;
use prometheus_client::registry::Registry;

/// Showcasing encoding of custom metrics.
///
/// Related to the concept of "Custom Collectors" in other implementations.
///
/// [`MyCustomMetric`] generates and encodes a random number on each scrape.
struct MyCustomMetric {}

impl EncodeMetric for MyCustomMetric {
fn encode(&self, mut encoder: Encoder) -> Result<(), std::io::Error> {
// This method is called on each Prometheus server scrape. Allowing you
// to execute whatever logic is needed to generate and encode your
// custom metric.
//
// While the `Encoder`'s builder pattern should guide you well and makes
// many mistakes impossible at the type level, do keep in mind that
// "with great power comes great responsibility". E.g. every CPU cycle
// spend in this method delays the response send to the Prometheus
// server.

encoder
.no_suffix()?
.no_bucket()?
.encode_value(rand::random::<u32>())?
.no_exemplar()?;

Ok(())
}

fn metric_type(&self) -> prometheus_client::metrics::MetricType {
MetricType::Unknown
}
}

fn main() {
let mut registry = Registry::default();

let metric = MyCustomMetric {};
registry.register(
"my_custom_metric",
"Custom metric returning a random number on each scrape",
metric,
);

let mut encoded = Vec::new();
encode(&mut encoded, &registry).unwrap();

println!("Scrape output:\n{:?}", String::from_utf8(encoded).unwrap());
}
22 changes: 17 additions & 5 deletions src/encoding/text.rs
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,8 @@ impl Encode for () {
}
}

/// Helper type for [`EncodeMetric`], see [`EncodeMetric::encode`].
///
// `Encoder` does not take a trait parameter for `writer` and `labels` because
// `EncodeMetric` which uses `Encoder` needs to be usable as a trait object in
// order to be able to register different metric types with a `Registry`. Trait
Expand All @@ -232,6 +234,7 @@ pub struct Encoder<'a, 'b> {
}

impl<'a, 'b> Encoder<'a, 'b> {
/// Encode a metric suffix, e.g. in the case of [`Counter`] the suffic `_total`.
pub fn encode_suffix(&mut self, suffix: &'static str) -> Result<BucketEncoder, std::io::Error> {
self.write_name_and_unit()?;

Expand All @@ -241,6 +244,7 @@ impl<'a, 'b> Encoder<'a, 'b> {
self.encode_labels()
}

/// Signal that the metric has no suffix.
pub fn no_suffix(&mut self) -> Result<BucketEncoder, std::io::Error> {
self.write_name_and_unit()?;

Expand Down Expand Up @@ -285,6 +289,7 @@ impl<'a, 'b> Encoder<'a, 'b> {
})
}

/// Encode a set of labels. Used by wrapper metric types like [`Family`].
pub fn with_label_set<'c, 'd>(&'c mut self, label_set: &'d dyn Encode) -> Encoder<'c, 'd> {
debug_assert!(self.labels.is_none());

Expand All @@ -305,7 +310,8 @@ pub struct BucketEncoder<'a> {
}

impl<'a> BucketEncoder<'a> {
fn encode_bucket(&mut self, upper_bound: f64) -> Result<ValueEncoder, std::io::Error> {
/// Encode a bucket. Used for the [`Histogram`] metric type.
pub fn encode_bucket(&mut self, upper_bound: f64) -> Result<ValueEncoder, std::io::Error> {
if self.opened_curly_brackets {
self.writer.write_all(b",")?;
} else {
Expand All @@ -325,7 +331,8 @@ impl<'a> BucketEncoder<'a> {
})
}

fn no_bucket(&mut self) -> Result<ValueEncoder, std::io::Error> {
/// Signal that the metric type has no bucket.
pub fn no_bucket(&mut self) -> Result<ValueEncoder, std::io::Error> {
if self.opened_curly_brackets {
self.writer.write_all(b"}")?;
}
Expand All @@ -341,7 +348,9 @@ pub struct ValueEncoder<'a> {
}

impl<'a> ValueEncoder<'a> {
fn encode_value<V: Encode>(&mut self, v: V) -> Result<ExemplarEncoder, std::io::Error> {
/// Encode the metric value. E.g. in the case of [`Counter`] the
/// monotonically increasing counter value.
pub fn encode_value<V: Encode>(&mut self, v: V) -> Result<ExemplarEncoder, std::io::Error> {
self.writer.write_all(b" ")?;
v.encode(self.writer)?;
Ok(ExemplarEncoder {
Expand All @@ -356,7 +365,8 @@ pub struct ExemplarEncoder<'a> {
}

impl<'a> ExemplarEncoder<'a> {
fn encode_exemplar<S: Encode, V: Encode>(
/// Encode an exemplar for the given metric.
pub fn encode_exemplar<S: Encode, V: Encode>(
&mut self,
exemplar: &Exemplar<S, V>,
) -> Result<(), std::io::Error> {
Expand All @@ -368,12 +378,14 @@ impl<'a> ExemplarEncoder<'a> {
Ok(())
}

fn no_exemplar(&mut self) -> Result<(), std::io::Error> {
/// Signal that the metric type has no exemplar.
pub fn no_exemplar(&mut self) -> Result<(), std::io::Error> {
self.writer.write_all(b"\n")?;
Ok(())
}
}

/// Trait implemented by each metric type, e.g. [`Counter`], to implement its encoding.
pub trait EncodeMetric {
fn encode(&self, encoder: Encoder) -> Result<(), std::io::Error>;

Expand Down