async-graphql/src/extensions/tracing.rs

70 lines
2.1 KiB
Rust
Raw Normal View History

2020-03-26 03:34:28 +00:00
use crate::extensions::{Extension, ResolveInfo};
use crate::{QueryPathSegment, Variables};
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
/// Tracing extension
///
/// # References
///
/// https://crates.io/crates/tracing
2020-08-30 20:32:14 +00:00
#[derive(Default)]
2020-04-28 07:01:19 +00:00
pub struct Tracing {
root_id: Option<Id>,
fields: BTreeMap<usize, Id>,
2020-03-26 03:34:28 +00:00
}
2020-04-28 07:01:19 +00:00
impl Extension for Tracing {
fn parse_start(&mut self, query_source: &str, _variables: &Variables) {
2020-04-28 07:01:19 +00:00
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.root_id.replace(id);
2020-04-28 07:01:19 +00:00
}
2020-03-26 03:34:28 +00:00
}
fn execution_end(&mut self) {
if let Some(id) = self.root_id.take() {
2020-04-28 07:01:19 +00:00
tracing::dispatcher::get_default(|d| d.exit(&id));
}
2020-03-26 03:34:28 +00:00
}
fn resolve_start(&mut self, info: &ResolveInfo<'_>) {
2020-04-28 07:01:19 +00:00
let parent_span = info
.resolve_id
.parent
.and_then(|id| self.fields.get(&id))
2020-04-28 07:01:19 +00:00
.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));
self.fields.insert(info.resolve_id.current, id);
2020-03-26 03:34:28 +00:00
}
}
fn resolve_end(&mut self, info: &ResolveInfo<'_>) {
if let Some(id) = self.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
}
}