1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
use crate::extensions::{Extension, ResolveInfo};
use crate::{QueryPathSegment, Variables};
use std::collections::BTreeMap;
use tracing::{span, Id, Level};

/// Tracing extension
///
/// # References
///
/// https://crates.io/crates/tracing
pub struct Tracing {
    root_id: Option<Id>,
    fields: BTreeMap<usize, Id>,
}

impl Extension for Tracing {
    fn parse_start(&mut self, query_source: &str, _variables: &Variables) {
        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);
        }
    }

    fn execution_end(&mut self) {
        if let Some(id) = self.root_id.take() {
            tracing::dispatcher::get_default(|d| d.exit(&id));
        }
    }

    fn resolve_start(&mut self, info: &ResolveInfo<'_>) {
        let parent_span = info
            .resolve_id
            .parent
            .and_then(|id| self.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));
            self.fields.insert(info.resolve_id.current, id);
        }
    }

    fn resolve_end(&mut self, info: &ResolveInfo<'_>) {
        if let Some(id) = self.fields.remove(&info.resolve_id.current) {
            tracing::dispatcher::get_default(|d| d.exit(&id));
        }
    }
}