async-graphql/src/extensions/logger.rs

136 lines
3.8 KiB
Rust
Raw Normal View History

2020-05-22 03:58:49 +00:00
use crate::extensions::{Extension, ResolveInfo};
use crate::{Error, Variables};
use async_graphql_parser::query::{Definition, Document, OperationDefinition, Selection};
2020-05-22 03:58:49 +00:00
use uuid::Uuid;
/// Logger extension
pub struct Logger {
id: Uuid,
enabled: bool,
query: String,
variables: Variables,
}
2020-05-22 03:58:49 +00:00
impl Default for Logger {
fn default() -> Self {
Self {
id: Uuid::new_v4(),
enabled: true,
query: String::new(),
variables: Default::default(),
}
2020-05-22 03:58:49 +00:00
}
}
impl Extension for Logger {
fn parse_start(&mut self, query_source: &str, variables: &Variables) {
self.query = query_source.replace(char::is_whitespace, "");
self.variables = variables.clone();
}
fn parse_end(&mut self, document: &Document) {
let mut is_schema = false;
for definition in document.definitions() {
if let Definition::Operation(operation) = &definition.node {
let selection_set = match &operation.node {
OperationDefinition::Query(query) => &query.selection_set,
OperationDefinition::SelectionSet(selection_set) => &selection_set.node,
_ => continue,
};
is_schema = selection_set.items.iter().any(|selection| {
if let Selection::Field(field) = &selection.node {
if field.name.as_str() == "__schema" {
return true;
}
}
false
});
if is_schema {
break;
}
}
}
if is_schema {
self.enabled = false;
return;
}
2020-07-15 10:05:24 +00:00
info!(
target = "async-graphql",
"Query",
id = self.id,
source = self.query,
variables = self.variables
);
2020-05-22 03:58:49 +00:00
}
fn resolve_start(&mut self, info: &ResolveInfo<'_>) {
if !self.enabled {
return;
}
2020-07-15 10:05:24 +00:00
trace!(
target = "async-graphql",
"Resolve start",
id = self.id,
path = info.path_node
);
2020-05-22 03:58:49 +00:00
}
fn resolve_end(&mut self, info: &ResolveInfo<'_>) {
if !self.enabled {
return;
}
2020-07-15 10:05:24 +00:00
trace!(
target = "async-graphql",
"Resolve end",
id = self.id,
path = info.path_node
);
2020-05-22 03:58:49 +00:00
}
fn error(&mut self, err: &Error) {
2020-05-22 03:58:49 +00:00
match err {
Error::Parse(err) => {
2020-07-15 10:05:24 +00:00
error!(
target = "async-graphql",
"Parse error",
id = self.id,
pos = err.pos,
query = self.query,
variables = self.variables,
message = err.message
);
2020-05-22 03:58:49 +00:00
}
Error::Query { pos, path, err } => {
2020-07-15 10:05:24 +00:00
error!(
target = "async-graphql",
"Query error",
id = self.id,
pos = pos,
path = path,
query = self.query,
variables = self.variables,
error = err,
);
2020-05-22 03:58:49 +00:00
}
Error::Rule { errors } => {
2020-07-15 10:05:24 +00:00
for err in errors {
error!(
target = "async-graphql",
"Validation error",
id = self.id,
pos = err.locations,
query = self.query,
variables = self.variables,
error = err.message,
);
2020-05-22 03:58:49 +00:00
}
}
}
}
}