Skip to content

Commit

Permalink
wip: log matching item in compact mode
Browse files Browse the repository at this point in the history
  • Loading branch information
SergioBenitez committed May 17, 2024
1 parent c5979c5 commit cf80426
Show file tree
Hide file tree
Showing 7 changed files with 74 additions and 23 deletions.
1 change: 1 addition & 0 deletions core/lib/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ impl Rocket<Orbit> {
upgrade: Option<hyper::upgrade::OnUpgrade>,
connection: ConnectionMeta,
) -> Result<hyper::Response<ReaderStream<ErasedResponse>>, http::Error> {
connection.trace_debug();
let request = ErasedRequest::new(self, parts, |rocket, parts| {
Request::from_hyp(rocket, parts, connection).unwrap_or_else(|e| e)
});
Expand Down
11 changes: 3 additions & 8 deletions core/lib/src/trace/subscriber/common.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,16 @@
use std::fmt;
use std::cell::Cell;
use std::sync::OnceLock;

use tracing::field::Field;
use tracing::{Level, Metadata};
use tracing_subscriber::prelude::*;
use tracing_subscriber::layer::Layered;
use tracing_subscriber::{reload, filter, Layer, Registry};
use tracing_subscriber::filter;
use tracing_subscriber::field::RecordFields;

use thread_local::ThreadLocal;
use yansi::{Condition, Paint, Style};

use crate::config::{Config, CliColors};
use crate::trace::subscriber::{RecordDisplay, RequestId, RequestIdLayer};
use crate::config::CliColors;
use crate::trace::subscriber::RecordDisplay;
use crate::util::Formatter;

mod private {
Expand All @@ -31,8 +28,6 @@ pub struct RocketFmt<K: private::FmtKind> {
pub(crate) style: Style,
}

pub type Handle<K> = reload::Handle<RocketFmt<K>, Layered<RequestIdLayer, Registry>>;

impl<K: private::FmtKind + Default + Copy> RocketFmt<K> {
pub(crate) fn state(&self) -> K {
self.state.get_or_default().get()
Expand Down
61 changes: 51 additions & 10 deletions core/lib/src/trace/subscriber/compact.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,19 @@ use std::fmt;
use std::time::Instant;
use std::num::NonZeroU64;

use time::OffsetDateTime;
use tracing::level_filters::LevelFilter;
use tracing::{Event, Level, Metadata, Subscriber};
use tracing::span::{Attributes, Id, Record};

use tracing_subscriber::layer::{Layer, Context};
use tracing_subscriber::registry::LookupSpan;
use tracing_subscriber::field::RecordFields;

use time::OffsetDateTime;
use yansi::{Paint, Painted};

use crate::util::Formatter;
use crate::trace::subscriber::{Data, RocketFmt};
use crate::http::{Status, StatusClass};
use super::RecordDisplay;

#[derive(Debug, Default, Copy, Clone)]
pub struct Compact {
Expand All @@ -26,13 +26,15 @@ pub struct Compact {
pub struct RequestData {
start: Instant,
fields: Data,
item: Option<(String, String)>,
}

impl RequestData {
pub fn new<T: RecordFields>(attrs: T) -> Self {
Self {
start: Instant::now(),
fields: Data::new(attrs),
item: None,
}
}
}
Expand Down Expand Up @@ -95,11 +97,17 @@ impl<S: Subscriber + for<'a> LookupSpan<'a>> Layer<S> for RocketFmt<Compact> {

fn on_event(&self, event: &Event<'_>, ctxt: Context<'_, S>) {
if let Some(id) = self.request_span_id() {
if event.metadata().name() == "response" {
let name = event.metadata().name();
if name == "response" {
let req_span = ctxt.span(&id).expect("on_event: req does not exist");
let mut exts = req_span.extensions_mut();
let data = exts.get_mut::<RequestData>().unwrap();
event.record(&mut data.fields);
} else if name == "catcher" || name == "route" {
let req_span = ctxt.span(&id).expect("on_event: req does not exist");
let mut exts = req_span.extensions_mut();
let data = exts.get_mut::<RequestData>().unwrap();
data.item = event.find_map_display("name", |v| (name.into(), v.to_string()))
}

if !self.in_debug() {
Expand Down Expand Up @@ -169,16 +177,49 @@ impl<S: Subscriber + for<'a> LookupSpan<'a>> Layer<S> for RocketFmt<Compact> {
let datetime = OffsetDateTime::now_utc() - elapsed;
let timestamp = self.timestamp_for(datetime);

let style = self.style(span.metadata());
let s = self.style(span.metadata());
let prefix = self.prefix(span.metadata());
let chevron = self.chevron(span.metadata());

println!("{prefix}{chevron} ({} {}ms) {} {} => {}",
timestamp.paint(style).primary().dim(),
let arrow = "→".paint(s.primary().bright());

let status_class = data.fields["status"].parse().ok()
.and_then(Status::from_code)
.map(|status| status.class());

let status_style = match status_class {
Some(StatusClass::Informational) => s,
Some(StatusClass::Success) => s.green(),
Some(StatusClass::Redirection) => s.magenta(),
Some(StatusClass::ClientError) => s.yellow(),
Some(StatusClass::ServerError) => s.red(),
Some(StatusClass::Unknown) => s.cyan(),
None => s.primary(),
};

let autohandle = Formatter(|f| {
match data.fields.get("autohandled") {
Some("true") => write!(f, " {} {}", "via".paint(s.dim()), "GET".paint(s)),
_ => Ok(())
}
});

let item = Formatter(|f| {
match &data.item {
Some((kind, name)) => write!(f,
"{} {} {arrow} ",
kind.paint(s),
name.paint(s.bold()),
),
None => Ok(())
}
});

println!("{prefix}{chevron} ({} {}ms) {}{autohandle} {} {arrow} {item}{}",
timestamp.paint(s).primary().dim(),
elapsed.as_millis(),
&data.fields["method"].paint(style),
&data.fields["method"].paint(s),
&data.fields["uri"],
&data.fields["status"],
&data.fields["status"].paint(status_style),
);
}
}
Expand Down
1 change: 0 additions & 1 deletion core/lib/src/trace/subscriber/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,4 @@ pub use common::RocketFmt;
pub use request_id::{RequestId, RequestIdLayer};
pub use dynamic::RocketDynFmt;

pub(crate) use common::Handle;
pub(crate) use visit::{RecordDisplay, Data};
6 changes: 2 additions & 4 deletions core/lib/src/trace/subscriber/pretty.rs
Original file line number Diff line number Diff line change
@@ -1,18 +1,16 @@
use std::fmt;
use std::sync::OnceLock;

use tracing::field::Field;
use tracing::{Event, Level, Metadata, Subscriber};
use tracing::span::{Attributes, Id, Record};
use tracing::field::Field;

use tracing_subscriber::layer::{Layer, Context};
use tracing_subscriber::registry::LookupSpan;
use tracing_subscriber::field::RecordFields;

use yansi::{Paint, Painted};

use crate::trace::subscriber::{Data, RecordDisplay, Handle, RocketFmt};
use crate::util::Formatter;
use crate::trace::subscriber::{Data, RecordDisplay, RocketFmt};

#[derive(Debug, Default, Copy, Clone)]
pub struct Pretty {
Expand Down
7 changes: 7 additions & 0 deletions core/lib/src/trace/subscriber/visit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use tracing_subscriber::field::RecordFields;
use crate::util::Formatter;

pub trait RecordDisplay: RecordFields {
fn find_map_display<T, F: Fn(&dyn fmt::Display) -> T>(&self, name: &str, f: F) -> Option<T>;
fn record_display<F: FnMut(&Field, &dyn fmt::Display)>(&self, f: F);
}

Expand Down Expand Up @@ -53,6 +54,12 @@ impl Visit for Data {
}

impl<T: RecordFields> RecordDisplay for T {
fn find_map_display<V, F: Fn(&dyn fmt::Display) -> V>(&self, name: &str, f: F) -> Option<V> {
let mut value = None;
self.record_display(|field, item| if field.name() == name { value = Some(f(item)); });
value
}

fn record_display<F: FnMut(&Field, &dyn fmt::Display)>(&self, f: F) {
struct DisplayVisit<F>(F);

Expand Down
10 changes: 10 additions & 0 deletions core/lib/src/trace/traceable.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use std::error::Error as StdError;

use crate::request::ConnectionMeta;
use crate::sentinel::Sentry;
use crate::util::Formatter;
use crate::{route, Catcher, Config, Error, Request, Response, Route};
Expand Down Expand Up @@ -270,6 +271,15 @@ impl Traceable for Request<'_> {
}
}

impl Traceable for ConnectionMeta {
fn trace(&self, level: Level) {
event!(level, "connection",
endpoint = self.peer_endpoint.as_ref().map(display),
certs = self.peer_certs.is_some(),
)
}
}

impl Traceable for ErrorKind {
fn trace(&self, level: Level) {
use ErrorKind::*;
Expand Down

0 comments on commit cf80426

Please sign in to comment.