1 unstable release

0.1.0 May 9, 2019

#26 in #facade

Download history 91/week @ 2024-07-22 118/week @ 2024-07-29 93/week @ 2024-08-05 102/week @ 2024-08-12 150/week @ 2024-08-19 185/week @ 2024-08-26 69/week @ 2024-09-02 108/week @ 2024-09-09 111/week @ 2024-09-16 172/week @ 2024-09-23 349/week @ 2024-09-30 168/week @ 2024-10-07 121/week @ 2024-10-14 179/week @ 2024-10-21 147/week @ 2024-10-28 78/week @ 2024-11-04

539 downloads per month
Used in 3 crates

0BSD license

14KB
199 lines

tracing_facade

A facade that aims to do for tracing what log does for logging.

CircleCI

License

This project is licensed under the Zero-Clause BSD License.


lib.rs:

A facade for tracing.

This crate provides a pluggable API for tracing, akin to what [log] does for logging.

Some available implementations are:

  • [tracing_chromium] - to emit Chromium's trace event format

Example

#[macro_use]
extern crate tracing_facade;

#[macro_use]
extern crate serde_json;

use std::borrow::Cow;
use std::sync::{Arc, Mutex};

#[derive(Clone, Debug)]
struct Event {
  name: String,
  kind: tracing_facade::EventKind,
  metadata: tracing_facade::Metadata,
}

impl<'a> From<tracing_facade::Event<'a>> for Event {
  fn from(event: tracing_facade::Event) -> Self {
    Event {
      name: event.name.into_owned(),
      kind: event.kind,
      metadata: event.metadata,
    }
  }
}

struct Tracer {
  events: Arc<Mutex<Vec<Event>>>
}

impl Tracer {
  fn new() -> (Tracer, Arc<Mutex<Vec<Event>>>) {
    let vec = Arc::new(Mutex::new(Vec::new()));
    let tracer = Tracer {
      events: Arc::clone(&vec)
    };
    (tracer, vec)
  }
}


impl tracing_facade::Tracer for Tracer {
  fn supports_metadata(&self) -> bool {
    true
  }

  fn record_event(&self, event: tracing_facade::Event) {
    self.events.lock().unwrap().push(event.into());
  }

  fn flush(&self) {}
}

fn main() {
  let (tracer, tracer_events) = Tracer::new();
  tracing_facade::set_boxed_tracer(Box::new(tracer));
  {
    trace_scoped!("foo");
    trace_begin!("bar", "value": 42);
    trace_end!("bar");
  }

  let events = tracer_events.lock().unwrap().clone();
  assert_eq!(events.len(), 4);
  assert_eq!(events[0].name, "foo");
  assert_eq!(events[0].kind, tracing_facade::EventKind::SyncBegin);
  assert_eq!(events[0].metadata.as_json(), None);

  assert_eq!(events[1].name, "bar");
  assert_eq!(events[1].kind, tracing_facade::EventKind::SyncBegin);
  assert_eq!(events[1].metadata.as_json(), Some(&json!({"value": 42})));

  assert_eq!(events[2].name, "bar");
  assert_eq!(events[2].kind, tracing_facade::EventKind::SyncEnd);
  assert_eq!(events[2].metadata.as_json(), None);

  assert_eq!(events[3].name, "foo");
  assert_eq!(events[3].kind, tracing_facade::EventKind::SyncEnd);
  assert_eq!(events[3].metadata.as_json(), None);
}

Dependencies

~0.5–1MB
~20K SLoC