Tracing on handlers #2053
-
Until Rocket has a built-in support for tracing, I am wrapping my handler with #[get("/abc?<params..>")]
pub async fn abc() -> Result<rocket::response::content::Json<String>, rocket::http::Status> {
let task = async {
..
};
task.instrument(tracing::info_span!(
"GET /abc"
)).await
} Now I want to add a Method1. Fairing + local_cache #[rocket::async_trait]
impl Fairing for TracingFairing {
fn info(&self) -> Info {
todo!()
}
async fn on_request(&self, req: &mut Request<'_>, _data: &mut Data<'_>) {
req.local_cache(|| {
info_span!(
&format!("{} {}", req.method(), req.url().path()),
)
});
}
async fn on_response<'r>(&self, req: &'r Request<'_>, res: &mut Response<'r>) {
let span: &Option<&Span> = req.local_cache(|| None);
if let Some(span) = span {
span.record("http.status", &res.status().code);
}
}
} it turns out Method2. #[get("/abc?<params..>")]
pub async fn abc(req: &Request<'_>) -> Result<rocket::response::content::Json<String>, rocket::http::Status> {
req.local_cache(|| {
info_span!("/abc")
});
..
} Method3. #[get("/abc?<params..>")]
pub async fn abc(req: &Request<'_>) -> Result<rocket::response::content::Json<String>, rocket::http::Status> {
let task = async { .. };
let result = task.await.respond_to(&req);
let code = match result {
Ok(response) => response.status().code,
Err(status) => status.code,
};
span.record("http.status", code);
response
} Is &Request as a parameter prohibited by design? Is there a good way to get status code, or add local_cache in the handler? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 8 replies
-
In general, please give more concrete examples, there are variables used which aren't declared, no clue what |
Beta Was this translation helpful? Give feedback.
Method #1
Do you have an example, I'm sure this would work
Method #2 & #3
Why would you need any of the request? You know your route as you specified it and you know what you gonna give back so you know what status code it will by, no need to call something with
respond_to
or what ever. Just do you business logic and you will know what your outcome is.In general, please give more concrete examples, there are variables used which aren't declared, no clue what
task
even is and what it returns that you could call a function on it.