async-graphql/src/extensions/tracing.rs

84 lines
2.4 KiB
Rust
Raw Normal View History

2020-03-26 03:34:28 +00:00
use crate::extensions::{Extension, ResolveInfo};
2020-04-28 07:01:19 +00:00
use crate::QueryPathSegment;
2020-03-26 03:34:28 +00:00
use parking_lot::Mutex;
2020-03-31 03:19:18 +00:00
use std::collections::BTreeMap;
2020-04-28 07:01:19 +00:00
use tracing::{span, Id, Level};
2020-03-26 03:34:28 +00:00
2020-04-28 07:01:19 +00:00
#[derive(Default)]
struct Inner {
root_id: Option<Id>,
fields: BTreeMap<usize, Id>,
2020-03-26 03:34:28 +00:00
}
2020-04-28 07:01:19 +00:00
/// Tracing extension
///
/// # References
///
/// https://crates.io/crates/tracing
pub struct Tracing {
inner: Mutex<Inner>,
2020-03-26 03:34:28 +00:00
}
2020-04-28 07:01:19 +00:00
impl Default for Tracing {
2020-03-26 03:34:28 +00:00
fn default() -> Self {
Self {
2020-04-28 07:01:19 +00:00
inner: Default::default(),
2020-03-26 03:34:28 +00:00
}
}
}
2020-04-28 07:01:19 +00:00
impl Extension for Tracing {
fn parse_start(&self, query_source: &str) {
let root_span = span!(target: "async-graphql", parent:None, Level::INFO, "query", source = query_source);
if let Some(id) = root_span.id() {
tracing::dispatcher::get_default(|d| d.enter(&id));
self.inner.lock().root_id.replace(id);
}
2020-03-26 03:34:28 +00:00
}
fn execution_end(&self) {
2020-04-28 07:01:19 +00:00
if let Some(id) = self.inner.lock().root_id.take() {
tracing::dispatcher::get_default(|d| d.exit(&id));
}
2020-03-26 03:34:28 +00:00
}
2020-05-22 03:58:49 +00:00
fn resolve_start(&self, info: &ResolveInfo<'_>) {
2020-03-26 03:34:28 +00:00
let mut inner = self.inner.lock();
2020-04-28 07:01:19 +00:00
let parent_span = info
.resolve_id
.parent
.and_then(|id| inner.fields.get(&id))
.cloned();
let span = match &info.path_node.segment {
QueryPathSegment::Index(idx) => span!(
target: "async-graphql",
parent: parent_span,
Level::INFO,
"field",
index = *idx,
parent_type = info.parent_type,
return_type = info.return_type
),
QueryPathSegment::Name(name) => span!(
target: "async-graphql",
parent: parent_span,
Level::INFO,
"field",
name = name,
parent_type = info.parent_type,
return_type = info.return_type
),
};
if let Some(id) = span.id() {
tracing::dispatcher::get_default(|d| d.enter(&id));
inner.fields.insert(info.resolve_id.current, id);
2020-03-26 03:34:28 +00:00
}
}
2020-05-22 03:58:49 +00:00
fn resolve_end(&self, info: &ResolveInfo<'_>) {
if let Some(id) = self.inner.lock().fields.remove(&info.resolve_id.current) {
2020-04-28 07:01:19 +00:00
tracing::dispatcher::get_default(|d| d.exit(&id));
}
2020-03-26 03:34:28 +00:00
}
}