Skip to content

Commit

Permalink
Allow dynamic selection of log format.
Browse files Browse the repository at this point in the history
  • Loading branch information
SergioBenitez committed Jun 3, 2024
1 parent cc2b159 commit 45264de
Show file tree
Hide file tree
Showing 20 changed files with 244 additions and 114 deletions.
2 changes: 1 addition & 1 deletion contrib/dyn_templates/src/template.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use rocket::fairing::Fairing;
use rocket::response::{self, Responder};
use rocket::http::{ContentType, Status};
use rocket::figment::{value::Value, error::Error};
use rocket::trace::Traceable;
use rocket::trace::Trace;
use rocket::serde::Serialize;

use crate::Engines;
Expand Down
2 changes: 1 addition & 1 deletion contrib/sync_db_pools/lib/src/connection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use rocket::fairing::{AdHoc, Fairing};
use rocket::request::{Request, Outcome, FromRequest};
use rocket::outcome::IntoOutcome;
use rocket::http::Status;
use rocket::trace::Traceable;
use rocket::trace::Trace;

use rocket::tokio::time::timeout;
use rocket::tokio::sync::{OwnedSemaphorePermit, Semaphore, Mutex};
Expand Down
2 changes: 1 addition & 1 deletion core/lib/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ thread_local = { version = "1.1", optional = true }
version = "0.3.18"
optional = true
default-features = false
features = ["fmt", "tracing-log"]
features = ["fmt", "tracing-log", "parking_lot"]

[dependencies.rocket_codegen]
version = "0.6.0-dev"
Expand Down
20 changes: 14 additions & 6 deletions core/lib/src/config/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use crate::config::{ShutdownConfig, Ident, CliColors};
use crate::request::{self, Request, FromRequest};
use crate::http::uncased::Uncased;
use crate::data::Limits;
use crate::trace::Traceable;
use crate::trace::{Trace, TraceFormat};

/// Rocket server configuration.
///
Expand All @@ -26,9 +26,10 @@ use crate::trace::Traceable;
/// the debug profile while [`Config::release_default()`] the default values for
/// the release profile. The [`Config::default()`] method automatically selects
/// the appropriate of the two based on the selected profile. With the exception
/// of `log_level`, which is `normal` in `debug` and `critical` in `release`,
/// and `secret_key`, which is regenerated from a random value if not set in
/// "debug" mode only, all default values are identical in all profiles.
/// of `log_level` and `log_format`, which are `info` / `pretty` in `debug` and
/// `error` / `compact` in `release`, and `secret_key`, which is regenerated
/// from a random value if not set in "debug" mode only, all default values are
/// identical in all profiles.
///
/// # Provider Details
///
Expand Down Expand Up @@ -124,6 +125,8 @@ pub struct Config {
/// Max level to log. **(default: _debug_ `info` / _release_ `error`)**
#[serde(with = "crate::trace::level")]
pub log_level: Option<Level>,
/// Format to use when logging. **(default: _debug_ `pretty` / _release_ `compact`)**
pub log_format: TraceFormat,
/// Whether to use colors and emoji when logging. **(default:
/// [`CliColors::Auto`])**
pub cli_colors: CliColors,
Expand Down Expand Up @@ -193,6 +196,7 @@ impl Config {
secret_key: SecretKey::zero(),
shutdown: ShutdownConfig::default(),
log_level: Some(Level::INFO),
log_format: TraceFormat::Pretty,
cli_colors: CliColors::Auto,
__non_exhaustive: (),
}
Expand All @@ -217,6 +221,7 @@ impl Config {
Config {
profile: Self::RELEASE_PROFILE,
log_level: Some(Level::ERROR),
log_format: TraceFormat::Compact,
..Config::debug_default()
}
}
Expand Down Expand Up @@ -354,6 +359,9 @@ impl Config {
/// The stringy parameter name for setting/extracting [`Config::log_level`].
pub const LOG_LEVEL: &'static str = "log_level";

/// The stringy parameter name for setting/extracting [`Config::log_format`].
pub const LOG_FORMAT: &'static str = "log_format";

/// The stringy parameter name for setting/extracting [`Config::shutdown`].
pub const SHUTDOWN: &'static str = "shutdown";

Expand All @@ -364,8 +372,8 @@ impl Config {
pub const PARAMETERS: &'static [&'static str] = &[
Self::WORKERS, Self::MAX_BLOCKING, Self::KEEP_ALIVE, Self::IDENT,
Self::IP_HEADER, Self::PROXY_PROTO_HEADER, Self::LIMITS,
Self::SECRET_KEY, Self::TEMP_DIR, Self::LOG_LEVEL, Self::SHUTDOWN,
Self::CLI_COLORS,
Self::SECRET_KEY, Self::TEMP_DIR, Self::LOG_LEVEL, Self::LOG_FORMAT,
Self::SHUTDOWN, Self::CLI_COLORS,
];

/// The stringy parameter name for setting/extracting [`Config::profile`].
Expand Down
2 changes: 1 addition & 1 deletion core/lib/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use std::sync::Arc;
use figment::Profile;

use crate::listener::Endpoint;
use crate::trace::Traceable;
use crate::trace::Trace;
use crate::{Ignite, Orbit, Phase, Rocket};

/// An error that occurs during launch.
Expand Down
2 changes: 1 addition & 1 deletion core/lib/src/lifecycle.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use futures::future::{FutureExt, Future};

use crate::{route, catcher, Rocket, Orbit, Request, Response, Data};
use crate::trace::Traceable;
use crate::trace::Trace;
use crate::util::Formatter;
use crate::data::IoHandler;
use crate::http::{Method, Status, Header};
Expand Down
4 changes: 2 additions & 2 deletions core/lib/src/rocket.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use figment::{Figment, Provider};
use futures::TryFutureExt;

use crate::shutdown::{Stages, Shutdown};
use crate::trace::{Traceable, TraceableCollection};
use crate::trace::{Trace, TraceAll};
use crate::{sentinel, shield::Shield, Catcher, Config, Route};
use crate::listener::{Bind, DefaultListener, Endpoint, Listener};
use crate::router::Router;
Expand Down Expand Up @@ -247,7 +247,7 @@ impl Rocket<Build> {
B::Error: fmt::Display,
M: Fn(&Origin<'a>, T) -> T,
F: Fn(&mut Self, T),
T: Clone + Traceable,
T: Clone + Trace,
{
let mut base = match base.clone().try_into() {
Ok(origin) => origin.into_owned(),
Expand Down
3 changes: 2 additions & 1 deletion core/lib/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ use crate::error::log_server_error;
use crate::data::{IoStream, RawStream};
use crate::util::{spawn_inspect, FutureExt, ReaderStream};
use crate::http::Status;
use crate::trace::{Traceable, TraceableCollection};
use crate::trace::{Trace, TraceAll};

type Result<T, E = crate::Error> = std::result::Result<T, E>;

Expand All @@ -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
2 changes: 1 addition & 1 deletion core/lib/src/trace/level.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ pub fn serialize<S: Serializer>(level: &Option<Level>, s: S) -> Result<S::Ok, S:
pub fn deserialize<'de, D: Deserializer<'de>>(de: D) -> Result<Option<Level>, D::Error> {
struct Visitor;

const E: &str = r#"one of "off", "error", "warn", "info", "debug", "trace", or a number 0-5"#;
const E: &str = r#"one of "off", "error", "warn", "info", "debug", "trace", or 0-5"#;

impl<'de> de::Visitor<'de> for Visitor {
type Value = Option<Level>;
Expand Down
21 changes: 15 additions & 6 deletions core/lib/src/trace/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,24 @@ pub mod subscriber;
pub(crate) mod level;

#[doc(inline)]
pub use traceable::{Traceable, TraceableCollection};
pub use traceable::{Trace, TraceAll};

#[doc(inline)]
pub use macros::*;

pub fn init<'a, T: Into<Option<&'a crate::Config>>>(_config: T) {
#[cfg(all(feature = "trace", debug_assertions))]
subscriber::RocketFmt::<subscriber::Pretty>::init(_config.into());
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, serde::Deserialize, serde::Serialize)]
#[serde(crate = "rocket::serde")]
pub enum TraceFormat {
#[serde(rename = "pretty")]
#[serde(alias = "PRETTY")]
Pretty,
#[serde(rename = "compact")]
#[serde(alias = "COMPACT")]
Compact
}

#[cfg(all(feature = "trace", not(debug_assertions)))]
subscriber::RocketFmt::<subscriber::Compact>::init(_config.into());
#[cfg_attr(nightly, doc(cfg(feature = "trace")))]
pub fn init<'a, T: Into<Option<&'a crate::Config>>>(config: T) {
#[cfg(feature = "trace")]
crate::trace::subscriber::RocketDynFmt::init(config.into())
}
50 changes: 10 additions & 40 deletions core/lib/src/trace/subscriber/common.rs
Original file line number Diff line number Diff line change
@@ -1,27 +1,23 @@
use std::fmt;
use std::cell::Cell;
use std::sync::OnceLock;

use tracing::{Level, Metadata};
use tracing::field::Field;

use tracing_subscriber::prelude::*;
use tracing_subscriber::layer::Layered;
use tracing_subscriber::{reload, filter, Layer, Registry};
use tracing::{Level, Metadata};
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 {
pub trait FmtKind: Default + Copy + Send + Sync + 'static { }
pub trait FmtKind: Send + Sync + 'static { }

impl FmtKind for crate::trace::subscriber::Pretty {}
impl FmtKind for crate::trace::subscriber::Compact {}
impl FmtKind for crate::trace::subscriber::Pretty { }
impl FmtKind for crate::trace::subscriber::Compact { }
}

#[derive(Default)]
Expand All @@ -32,9 +28,7 @@ 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> RocketFmt<K> {
impl<K: private::FmtKind + Default + Copy> RocketFmt<K> {
pub(crate) fn state(&self) -> K {
self.state.get_or_default().get()
}
Expand All @@ -45,33 +39,9 @@ impl<K: private::FmtKind> RocketFmt<K> {
update(&mut old);
cell.set(old);
}
}

pub(crate) fn init_with(config: Option<&Config>, handle: &OnceLock<Handle<K>>)
where Self: Layer<Layered<RequestIdLayer, Registry>>
{
// Do nothing if there's no config and we've already initialized.
if config.is_none() && handle.get().is_some() {
return;
}

let workers = config.map(|c| c.workers).unwrap_or(num_cpus::get());
let cli_colors = config.map(|c| c.cli_colors).unwrap_or(CliColors::Auto);
let log_level = config.map(|c| c.log_level).unwrap_or(Some(Level::INFO));

let formatter = RocketFmt::new(workers, cli_colors, log_level);
let (layer, reload_handle) = reload::Layer::new(formatter);
let result = tracing_subscriber::registry()
.with(RequestId::layer())
.with(layer)
.try_init();

if result.is_ok() {
assert!(handle.set(reload_handle).is_ok());
} if let Some(handle) = handle.get() {
assert!(handle.modify(|layer| layer.reset(cli_colors, log_level)).is_ok());
}
}

impl<K: private::FmtKind> RocketFmt<K> {
pub fn new(workers: usize, cli_colors: CliColors, level: Option<Level>) -> Self {
Self {
state: ThreadLocal::with_capacity(workers),
Expand Down
Loading

0 comments on commit 45264de

Please sign in to comment.