metrique is a crate to emit unit-of-work metrics
- [
#[metrics]macro reference]
Unlike many popular metric frameworks that are based on the concept of your application having a fixed-ish set of counters and gauges, which are periodically updated to a central place, metrique is based on the concept of structured metric records. Your application emits a series of metric records - that are essentially structured log entries - to an observability service such as Amazon CloudWatch, and the observability service allows you to view and alarm on complex aggregations of the metrics.
The log entries being structured means that you can easily use problem-specific aggregations to track down the cause of issues, rather than only observing the symptoms.
Further reading
_guide::cookbook- principles for effective instrumentation and choosing the right pattern_guide::concurrency- flush guards, slots, atomics, and shared handles for concurrent metrics_guide::sinks- destinations, sink types, and alternatives toServiceMetrics_guide::sampling- congressional sampling and the tee pattern for high-volume services_guide::testing- test utilities and debugging common issues
[#[metrics] macro reference]: https://docs.rs/metrique/latest/metrique/unit_of_work/attr.metrics.html
[macro documentation]: https://docs.rs/metrique/latest/metrique/unit_of_work/attr.metrics.html#enums
[sinks other than ServiceMetrics]: https://docs.rs/metrique/latest/metrique/_guide/sinks/#sinks-other-than-servicemetrics
[sampling guide]: https://docs.rs/metrique/latest/metrique/_guide/sampling/
[testing guide]: https://docs.rs/metrique/latest/metrique/_guide/testing/
Getting Started (Applications)
Most metrics your application records will be "unit of work" metrics. In a classic HTTP server, these are typically tied to the request/response scope.
You declare a struct that represents the metrics you plan to capture over the course of the request and annotate it with #[metrics]. That makes it possible to write it to a Sink. Rather than writing to the sink directly, you typically use append_on_drop(sink) to obtain a guard that will automatically write to the sink when dropped.
The simplest way to emit the entry is by emitting it to the ServiceMetrics global sink. That is a global
rendezvous point - you can attach a destination by using attach or attach_to_stream, and then write to it
by using the sink method (you must attach a destination before calling sink, otherwise you will encounter
a panic!).
If the global sink is not suitable, see
[sinks other than ServiceMetrics].
The example below will write the metrics to a tracing_appender::rolling::RollingFileAppender
in EMF format.
use PathBuf;
use metrics;
use ;
use Millisecond;
use ServiceMetrics;
use GlobalEntrySink;
use ;
use Emf;
use ;
// Define operation as an enum (you can also define operation as a &'static str).
// Enums containing fields are also supported - see <#entry-enums>
// define our metrics struct
async
async
That code will create a single metric line (your timestamp and OperationTime may vary).
Getting Started (Libraries)
Library operations should normally return a struct implementing CloseEntry that contains the metrics for their operation. Generally, the best way of getting that is by just using the #[metrics] macro:
use Instrumented;
use Timer;
use Millisecond;
use metrics;
use io;
async
Note that we do not use rename_all - the application should be able to choose the naming style.
Read docs/usage_in_libraries.md for more details
Common Patterns
For more complex examples, see the examples folder.
Entry Enums
Enums can be used as entries with different fields per variant. See the [macro documentation] for details.
Entry enums handle container and field-level attributes like structs. You can optionally include a "tag" field that contains the variant name.
use metrics;
// generally entry enums will be used as subfields,
// though they can also be root containers
When RequestMetrics with Operation::MeetDogs { dogs_met: 3 } is emitted, the output includes:
operation(string value):"MeetDogs"dogs_met(metric):3
When RequestMetrics with Operation::FindGoose { goose_found: true } is emitted, the output includes:
operation(string value):"FindGoose"goose_found(metric):1(booleans emit as 0 or 1)
When RequestMetrics with Operation::CountCats(CatMetrics { cats_counted: 7 }) is emitted, the output includes:
operation(string value):"CountCats"cats_counted(metric):7
Timing Events
metrique provides several timing primitives to simplify measuring time. They are all mockable via
metrique_timesource.
-
Timer/Stopwatch: Reports aDurationusing theInstanttime-source. It can either be aTimer(in which case it starts as soon as it is created), or aStopwatch(in which case you must start it manually). In all cases, if you don't stop it manually, it will drop when the record containing it is closed. -
Timestamp: records a timestamp using theSystemTimetime-source. When used with#[metrics(timestamp)], it will be written as the canonical timestamp field for whatever format is in use. Otherwise, it will report its value as a string property containing the duration since the Unix Epoch.You can control the formatting of a
Timestamp(that is not used as a#[metrics(timestamp)]- the formatting of the canonical timestamp is controlled solely by the formatter) by setting#[metrics(format = ...)]to one ofEpochSeconds,EpochMillis(the default), orEpochMicros. -
TimestampOnClose: records the timestamp when the record is closed.
Usage example:
use ;
use Millisecond;
use EpochSeconds;
use metrics;
use Duration;
Returning Metrics from Subcomponents
#[metrics] are composable. There are two main patterns for subcomponents
recording their own metrics. You can define sub-metrics by having a
#[metrics(subfield)]. Then, you can either return a metric struct along with
the data - metrique provides Instrument to standardize this - or pass a
(mutable) reference to the metrics struct. See the library metrics example.
This is the recommended approach. It has minimal performance overhead and makes your metrics very predictable.
Metrics with complex lifetimes
Sometimes, managing metrics with a simple ownership and mutable reference pattern does not work well -
for example when spawning background tasks or fanning out work in parallel. metrique provides flush
guards, Slots, atomics, and shared handles to cover these cases.
See _guide::concurrency for details and examples.
Using sampling to deal with too-many-metrics
Generally, metrique is fast enough to preserve everything as a full event. But this isn't always possible. Before you reach for client side aggregation, consider [sampling][sampling guide].
Controlling metric output
Setting units for metrics
You can provide units for your metrics. These will be included in the output format. You can find all available units in metrique::unit::*. Note that these are an open set and the custom units may be defined.
use metrics;
use Megabyte;
Renaming metric fields
the complex interaction between naming, prefixing, and inflection is deterministic, but sometimes might not do what you expect. It is critical that you add [tests][testing guide] that validate that the keys being produced match your expectations
You can customize how metric field names appear in the output using several approaches:
Rename all fields with a consistent case style
Use the rename_all attribute on the struct to apply a consistent naming convention to all fields:
use metrics;
// All fields will use kebab-case in the output
Supported case styles include: "PascalCase", "camelCase", "snake_case".
Important: rename_all is transitive—it will apply to all child structures that are #[metrics(flatten)]'d into the entry. You SHOULD only set rename_all on your root struct. If a struct explicitly sets a name scheme with rename_all, it will not be overridden by a parent.
Add a prefix to all fields
Use the prefix attribute on structs to add a consistent prefix to all fields:
use metrics;
// All fields will be prefixed with "api_"
Add a prefix to all metrics in a subfield
Use the prefix attribute on flatten to add a consistent prefix to fields of the
included struct:
use metrics;
use HashMap;
// using `subfield_owned` to allow closing over the `HashMap`
Prefixes will be inflected to the case metrics are emitted in, so if you let rename_all
vary, the inner metric name will be:
- in
rename_all = "Preserve",Downstreamsuccess/OtherDownstreamsuccess - in
rename_all = "PascalCase",DownstreamSuccess/OtherDownstreamSuccess - in
rename_all = "kebab-case",downstream-success/other-downstream-success - in
rename_all = "snake_case",downstream_success/other_downstream_success
Rename individual fields
Use the name attribute on individual fields to override their names:
use metrics;
Combining renaming strategies
You can combine these approaches, with field-level renames taking precedence over container-level rules:
use metrics;
Types in metrics
Example of a metrics struct:
use ;
use ;
use ;
use metrics;
use ToString;
use IpAddr;
use ;
use Duration;
Ordinary fields in metrics need to implement CloseValue<Output: metrique_writer::Value>.
If you use a formatter (#[metrics(format)]), your field needs to implement CloseValue,
and its output needs to be supported by the formatter instead of
implementing metrique_writer::Value.
Nested fields (#[metrics(flatten)]) need to implement CloseEntry.
Customization
If the standard primitives in metrique don't serve your needs, there's a good
chance you might be able to implement them yourself.
Custom CloseValue and CloseValueRef
If you want to change the behavior when metrics are closed, you can
implement CloseValue or CloseValueRef yourself (CloseValueRef
does not take ownership and will also also work behind smart pointers,
for example for Arc<YourValue>).
For instance, here is an example for adding a custom timer type that calculates the time from when it was created, to when it finished, on close (it doesn't do anything that timers::Timer doesn't do, but is useful as an example).
use ;
use ;
;
// this does not take ownership, and therefore should implement `CloseValue` for both &T and T
Custom ValueFormatters
You can implement custom formatters by creating a custom value formatter using the ValueFormatter trait that formats the value into a ValueWriter, then referring to it using #[metrics(format)].
An example use would look like the following:
use metrics;
use SystemTime;
use ;
/// Format a SystemTime as UTC time
;
// observe that `format_value` is a static method, so `AsUtcDate`
// is never initialized.
Destinations
metrique metrics are normally written via a background queue to a file, stdout, or a network socket.
The global ServiceMetrics sink is the easiest way to get started, but you can also create
locally-defined global sinks or use EntrySink directly for non-global or specifically-typed sinks.
See _guide::sinks for details on sink types, destinations,
and alternatives to ServiceMetrics.
Sampling
High-volume services may want to sample metrics to reduce CPU and agent load. metrique supports
fixed-fraction sampling and a congressional sampler that preserves rare events. A common pattern is
to tee metrics into an archived log of record and a sampled stream for CloudWatch.
See _guide::sampling for details and a full example.
Testing
metrique provides test utilities for introspecting emitted entries without reading EMF directly.
Use TestEntrySink to capture entries and assert on their values and metrics.
See _guide::testing for details, examples, and
debugging tips.
Security Concerns
Sensitive information in metrics
Metrics and logs are often exported to places where they can be read by a large number of people. Therefore, it is important to keep sensitive information, including secret keys and private information, out of them.
The metrique library intentionally does not have mechanisms that put unexpected data within metric entries (for example, bridges from Debug implementations that can put unexpected struct fields in metrics).
However, the metrique library controls neither the information placed in metric entries nor where the metrics end up. Therefore, it is your responsibility of an application writer to avoid using the metrique library to emit sensitive information to where it shouldn't be present.
Metrics being dropped
The metrique library is intended to be used for operational metrics, and therefore it is intentionally designed to drop metrics under high-load conditions rather than having the application grind to a halt.
There are 2 main places where this can happen:
BackgroundQueuewill drop the earliest metric in the queue under load.- It is possible to explicitly enable sampling (by using
sample_by_fixed_fractionorsample_by_congress_at_fixed_entries_per_second). If sampling is being used, metrics will be dropped at random.
If your application's security relies on metric entries not being dropped (for example, if you use metric entries to track user log-in operations, and your application relies on log-in operations not being dropped), it is your responsibility to engineer your application to avoid the metrics being dropped.
In that case, you should not be using BackgroundQueue or sampling. It is probably fine to use the Format implementations in that case, but it is recommended to test and audit your use-case to make sure nothing is being missed.
Use of exporters
The metrique library does not currently contain any code that exports the metrics outside of the current process. To make a working system, you normally need to integrate the metrique library with some exporter such as the Amazon CloudWatch Agent.
It is your responsibility to ensure that any agents you are using are kept up to date and configured in a secure manner.