mirror of
https://github.com/tokio-rs/tokio.git
synced 2026-08-19 00:00:09 +02:00
<!-- Thank you for your Pull Request. Please provide a description above and review the requirements below. Bug fixes and new features should include tests. Contributors guide: https://github.com/tokio-rs/tokio/blob/master/CONTRIBUTING.md --> ## Motivation In asynchronous systems like Tokio, interpreting traditional log messages can often be quite challenging. Since individual tasks are multiplexed on the same thread, associated events and log lines are intermixed making it difficult to trace the logic flow. Currently, none of the available logging frameworks or libraries in Rust offer the ability to trace logical paths through a futures-based program. There also are complementary goals that can be accomplished with such a system. For example, metrics / instrumentation can be tracked by observing emitted events, or trace data can be exported to a distributed tracing or event processing system. In addition, it can often be useful to generate this diagnostic data in a structured manner that can be consumed programmatically. While prior art for structured logging in Rust exists, it is not currently standardized, and is not "Tokio-friendly". ## Solution This branch adds a new library to the tokio project, `tokio-trace`. `tokio-trace` expands upon logging-style diagnostics by allowing libraries and applications to record structured events with additional information about *temporality* and *causality* --- unlike a log message, a span in `tokio-trace` has a beginning and end time, may be entered and exited by the flow of execution, and may exist within a nested tree of similar spans. In addition, `tokio-trace` spans are *structured*, with the ability to record typed data as well as textual messages. The `tokio-trace-core` crate contains the core primitives for this system, which are expected to remain stable, while `tokio-trace` crate provides a more "batteries-included" API. In particular, it provides macros which are a superset of the `log` crate's `error!`, `warn!`, `info!`, `debug!`, and `trace!` macros, allowing users to begin the process of adopting `tokio-trace` by performing a drop-in replacement. ## Notes Work on this project had previously been carried out in the [tokio-trace-prototype] repository. In addition to the `tokio-trace` and `tokio-trace-core` crates, the `tokio-trace-prototype` repo also contains prototypes or sketches of adapter, compatibility, and utility crates which provide useful functionality for `tokio-trace`, but these crates are not yet ready for a release. When this branch is merged, that repository will be archived, and the remaining unstable crates will be moved to a new `tokio-trace-nursery` repository. Remaining issues on the `tokio-trace-prototype` repo will be moved to the appropriate new repo. The crates added in this branch are not _identical_ to the current head of the `tokio-trace-prototype` repo, as I did some final clean-up and docs polish in this branch prior to merging this PR. [tokio-trace-prototype]: https://github.com/hawkw/tokio-trace-prototype Closes: #561 Signed-off-by: Eliza Weisman <[email protected]>
225 lines
5.7 KiB
Rust
225 lines
5.7 KiB
Rust
use tokio_trace::{
|
|
callsite::Callsite,
|
|
field::{self, Field, Record, Value},
|
|
};
|
|
|
|
use std::{collections::HashMap, fmt};
|
|
|
|
#[derive(Default, Debug, Eq, PartialEq)]
|
|
pub struct Expect {
|
|
fields: HashMap<String, MockValue>,
|
|
only: bool,
|
|
}
|
|
|
|
#[derive(Debug)]
|
|
pub struct MockField {
|
|
name: String,
|
|
value: MockValue,
|
|
}
|
|
|
|
#[derive(Debug, Eq, PartialEq)]
|
|
pub enum MockValue {
|
|
I64(i64),
|
|
U64(u64),
|
|
Bool(bool),
|
|
Str(String),
|
|
Debug(String),
|
|
Any,
|
|
}
|
|
|
|
pub fn mock<K>(name: K) -> MockField
|
|
where
|
|
String: From<K>,
|
|
{
|
|
MockField {
|
|
name: name.into(),
|
|
value: MockValue::Any,
|
|
}
|
|
}
|
|
|
|
impl MockField {
|
|
/// Expect a field with the given name and value.
|
|
pub fn with_value(self, value: &Value) -> Self {
|
|
Self {
|
|
value: MockValue::from(value),
|
|
..self
|
|
}
|
|
}
|
|
|
|
pub fn and(self, other: MockField) -> Expect {
|
|
Expect {
|
|
fields: HashMap::new(),
|
|
only: false,
|
|
}
|
|
.and(self)
|
|
.and(other)
|
|
}
|
|
|
|
pub fn only(self) -> Expect {
|
|
Expect {
|
|
fields: HashMap::new(),
|
|
only: true,
|
|
}
|
|
.and(self)
|
|
}
|
|
}
|
|
|
|
impl Into<Expect> for MockField {
|
|
fn into(self) -> Expect {
|
|
Expect {
|
|
fields: HashMap::new(),
|
|
only: false,
|
|
}
|
|
.and(self)
|
|
}
|
|
}
|
|
|
|
impl Expect {
|
|
pub fn and(mut self, field: MockField) -> Self {
|
|
self.fields.insert(field.name, field.value);
|
|
self
|
|
}
|
|
|
|
/// Indicates that no fields other than those specified should be expected.
|
|
pub fn only(self) -> Self {
|
|
Self { only: true, ..self }
|
|
}
|
|
|
|
fn compare_or_panic(&mut self, name: &str, value: &Value, ctx: &str) {
|
|
let value = value.into();
|
|
match self.fields.remove(name) {
|
|
Some(MockValue::Any) => {}
|
|
Some(expected) => assert!(
|
|
expected == value,
|
|
"\nexpected `{}` to contain:\n\t`{}{}`\nbut got:\n\t`{}{}`",
|
|
ctx,
|
|
name,
|
|
expected,
|
|
name,
|
|
value
|
|
),
|
|
None if self.only => panic!(
|
|
"\nexpected `{}` to contain only:\n\t`{}`\nbut got:\n\t`{}{}`",
|
|
ctx, self, name, value
|
|
),
|
|
_ => {}
|
|
}
|
|
}
|
|
|
|
pub fn checker<'a>(&'a mut self, ctx: String) -> CheckRecorder<'a> {
|
|
CheckRecorder { expect: self, ctx }
|
|
}
|
|
|
|
pub fn is_empty(&self) -> bool {
|
|
self.fields.is_empty()
|
|
}
|
|
}
|
|
|
|
impl fmt::Display for MockValue {
|
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
|
match self {
|
|
MockValue::I64(v) => write!(f, ": i64 = {:?}", v),
|
|
MockValue::U64(v) => write!(f, ": u64 = {:?}", v),
|
|
MockValue::Bool(v) => write!(f, ": bool = {:?}", v),
|
|
MockValue::Str(v) => write!(f, ": &str = {:?}", v),
|
|
MockValue::Debug(v) => write!(f, ": &fmt::Debug = {:?}", v),
|
|
MockValue::Any => write!(f, ": _ = _"),
|
|
}
|
|
}
|
|
}
|
|
|
|
pub struct CheckRecorder<'a> {
|
|
expect: &'a mut Expect,
|
|
ctx: String,
|
|
}
|
|
|
|
impl<'a> Record for CheckRecorder<'a> {
|
|
fn record_i64(&mut self, field: &Field, value: i64) {
|
|
self.expect
|
|
.compare_or_panic(field.name(), &value, &self.ctx[..])
|
|
}
|
|
|
|
fn record_u64(&mut self, field: &Field, value: u64) {
|
|
self.expect
|
|
.compare_or_panic(field.name(), &value, &self.ctx[..])
|
|
}
|
|
|
|
fn record_bool(&mut self, field: &Field, value: bool) {
|
|
self.expect
|
|
.compare_or_panic(field.name(), &value, &self.ctx[..])
|
|
}
|
|
|
|
fn record_str(&mut self, field: &Field, value: &str) {
|
|
self.expect
|
|
.compare_or_panic(field.name(), &value, &self.ctx[..])
|
|
}
|
|
|
|
fn record_debug(&mut self, field: &Field, value: &fmt::Debug) {
|
|
self.expect
|
|
.compare_or_panic(field.name(), &field::debug(value), &self.ctx)
|
|
}
|
|
}
|
|
|
|
impl<'a> CheckRecorder<'a> {
|
|
pub fn finish(self) {
|
|
assert!(
|
|
self.expect.fields.is_empty(),
|
|
"{}missing {}",
|
|
self.expect,
|
|
self.ctx
|
|
);
|
|
}
|
|
}
|
|
|
|
impl<'a> From<&'a Value> for MockValue {
|
|
fn from(value: &'a Value) -> Self {
|
|
struct MockValueBuilder {
|
|
value: Option<MockValue>,
|
|
}
|
|
|
|
impl Record for MockValueBuilder {
|
|
fn record_i64(&mut self, _: &Field, value: i64) {
|
|
self.value = Some(MockValue::I64(value));
|
|
}
|
|
|
|
fn record_u64(&mut self, _: &Field, value: u64) {
|
|
self.value = Some(MockValue::U64(value));
|
|
}
|
|
|
|
fn record_bool(&mut self, _: &Field, value: bool) {
|
|
self.value = Some(MockValue::Bool(value));
|
|
}
|
|
|
|
fn record_str(&mut self, _: &Field, value: &str) {
|
|
self.value = Some(MockValue::Str(value.to_owned()));
|
|
}
|
|
|
|
fn record_debug(&mut self, _: &Field, value: &fmt::Debug) {
|
|
self.value = Some(MockValue::Debug(format!("{:?}", value)));
|
|
}
|
|
}
|
|
|
|
let fake_field = callsite!(name: "fake", fields: fake_field)
|
|
.metadata()
|
|
.fields()
|
|
.field("fake_field")
|
|
.unwrap();
|
|
let mut builder = MockValueBuilder { value: None };
|
|
value.record(&fake_field, &mut builder);
|
|
builder
|
|
.value
|
|
.expect("finish called before a value was recorded")
|
|
}
|
|
}
|
|
|
|
impl fmt::Display for Expect {
|
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
|
write!(f, "fields ")?;
|
|
let entries = self
|
|
.fields
|
|
.iter()
|
|
.map(|(k, v)| (field::display(k), field::display(v)));
|
|
f.debug_map().entries(entries).finish()
|
|
}
|
|
}
|