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
use rocket::fairing::{Fairing, Info, Kind};
use rocket::{Data, Request, Response};
use sentry::{Breadcrumb, Level};
use serde_json::{json, Value};
use std::collections::BTreeMap;
pub struct LoggerFairing;
impl Fairing for LoggerFairing {
fn info(&self) -> Info {
Info {
name: "Sentry logger",
kind: Kind::Request | Kind::Response,
}
}
fn on_request(&self, request: &mut Request, _: &Data) {
let data: BTreeMap<String, Value> = vec![
("url".into(), json!(request.uri().path())),
("method".into(), json!(request.method().as_str())),
]
.into_iter()
.collect();
let breadcrumb = Breadcrumb {
ty: "http".into(),
category: Some("request".into()),
data,
..Default::default()
};
sentry::add_breadcrumb(breadcrumb);
}
fn on_response(&self, _request: &Request, response: &mut Response) {
let body_str = response.body_string().unwrap_or_default();
let body: Value = serde_json::from_str(&body_str).unwrap_or_default();
if response.status().code >= 400 {
sentry::capture_message(&body_str, Level::Error);
}
if let Value::Bool(false) = body["success"] {
sentry::capture_message(&body_str, Level::Error);
}
}
}