Skip to content

Commit 45264de

Browse files
committed
Allow dynamic selection of log format.
1 parent cc2b159 commit 45264de

File tree

20 files changed

+244
-114
lines changed

20 files changed

+244
-114
lines changed

contrib/dyn_templates/src/template.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use rocket::fairing::Fairing;
77
use rocket::response::{self, Responder};
88
use rocket::http::{ContentType, Status};
99
use rocket::figment::{value::Value, error::Error};
10-
use rocket::trace::Traceable;
10+
use rocket::trace::Trace;
1111
use rocket::serde::Serialize;
1212

1313
use crate::Engines;

contrib/sync_db_pools/lib/src/connection.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ use rocket::fairing::{AdHoc, Fairing};
66
use rocket::request::{Request, Outcome, FromRequest};
77
use rocket::outcome::IntoOutcome;
88
use rocket::http::Status;
9-
use rocket::trace::Traceable;
9+
use rocket::trace::Trace;
1010

1111
use rocket::tokio::time::timeout;
1212
use rocket::tokio::sync::{OwnedSemaphorePermit, Semaphore, Mutex};

core/lib/Cargo.toml

+1-1
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ thread_local = { version = "1.1", optional = true }
8484
version = "0.3.18"
8585
optional = true
8686
default-features = false
87-
features = ["fmt", "tracing-log"]
87+
features = ["fmt", "tracing-log", "parking_lot"]
8888

8989
[dependencies.rocket_codegen]
9090
version = "0.6.0-dev"

core/lib/src/config/config.rs

+14-6
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ use crate::config::{ShutdownConfig, Ident, CliColors};
1010
use crate::request::{self, Request, FromRequest};
1111
use crate::http::uncased::Uncased;
1212
use crate::data::Limits;
13-
use crate::trace::Traceable;
13+
use crate::trace::{Trace, TraceFormat};
1414

1515
/// Rocket server configuration.
1616
///
@@ -26,9 +26,10 @@ use crate::trace::Traceable;
2626
/// the debug profile while [`Config::release_default()`] the default values for
2727
/// the release profile. The [`Config::default()`] method automatically selects
2828
/// the appropriate of the two based on the selected profile. With the exception
29-
/// of `log_level`, which is `normal` in `debug` and `critical` in `release`,
30-
/// and `secret_key`, which is regenerated from a random value if not set in
31-
/// "debug" mode only, all default values are identical in all profiles.
29+
/// of `log_level` and `log_format`, which are `info` / `pretty` in `debug` and
30+
/// `error` / `compact` in `release`, and `secret_key`, which is regenerated
31+
/// from a random value if not set in "debug" mode only, all default values are
32+
/// identical in all profiles.
3233
///
3334
/// # Provider Details
3435
///
@@ -124,6 +125,8 @@ pub struct Config {
124125
/// Max level to log. **(default: _debug_ `info` / _release_ `error`)**
125126
#[serde(with = "crate::trace::level")]
126127
pub log_level: Option<Level>,
128+
/// Format to use when logging. **(default: _debug_ `pretty` / _release_ `compact`)**
129+
pub log_format: TraceFormat,
127130
/// Whether to use colors and emoji when logging. **(default:
128131
/// [`CliColors::Auto`])**
129132
pub cli_colors: CliColors,
@@ -193,6 +196,7 @@ impl Config {
193196
secret_key: SecretKey::zero(),
194197
shutdown: ShutdownConfig::default(),
195198
log_level: Some(Level::INFO),
199+
log_format: TraceFormat::Pretty,
196200
cli_colors: CliColors::Auto,
197201
__non_exhaustive: (),
198202
}
@@ -217,6 +221,7 @@ impl Config {
217221
Config {
218222
profile: Self::RELEASE_PROFILE,
219223
log_level: Some(Level::ERROR),
224+
log_format: TraceFormat::Compact,
220225
..Config::debug_default()
221226
}
222227
}
@@ -354,6 +359,9 @@ impl Config {
354359
/// The stringy parameter name for setting/extracting [`Config::log_level`].
355360
pub const LOG_LEVEL: &'static str = "log_level";
356361

362+
/// The stringy parameter name for setting/extracting [`Config::log_format`].
363+
pub const LOG_FORMAT: &'static str = "log_format";
364+
357365
/// The stringy parameter name for setting/extracting [`Config::shutdown`].
358366
pub const SHUTDOWN: &'static str = "shutdown";
359367

@@ -364,8 +372,8 @@ impl Config {
364372
pub const PARAMETERS: &'static [&'static str] = &[
365373
Self::WORKERS, Self::MAX_BLOCKING, Self::KEEP_ALIVE, Self::IDENT,
366374
Self::IP_HEADER, Self::PROXY_PROTO_HEADER, Self::LIMITS,
367-
Self::SECRET_KEY, Self::TEMP_DIR, Self::LOG_LEVEL, Self::SHUTDOWN,
368-
Self::CLI_COLORS,
375+
Self::SECRET_KEY, Self::TEMP_DIR, Self::LOG_LEVEL, Self::LOG_FORMAT,
376+
Self::SHUTDOWN, Self::CLI_COLORS,
369377
];
370378

371379
/// The stringy parameter name for setting/extracting [`Config::profile`].

core/lib/src/error.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use std::sync::Arc;
77
use figment::Profile;
88

99
use crate::listener::Endpoint;
10-
use crate::trace::Traceable;
10+
use crate::trace::Trace;
1111
use crate::{Ignite, Orbit, Phase, Rocket};
1212

1313
/// An error that occurs during launch.

core/lib/src/lifecycle.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use futures::future::{FutureExt, Future};
22

33
use crate::{route, catcher, Rocket, Orbit, Request, Response, Data};
4-
use crate::trace::Traceable;
4+
use crate::trace::Trace;
55
use crate::util::Formatter;
66
use crate::data::IoHandler;
77
use crate::http::{Method, Status, Header};

core/lib/src/rocket.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ use figment::{Figment, Provider};
1111
use futures::TryFutureExt;
1212

1313
use crate::shutdown::{Stages, Shutdown};
14-
use crate::trace::{Traceable, TraceableCollection};
14+
use crate::trace::{Trace, TraceAll};
1515
use crate::{sentinel, shield::Shield, Catcher, Config, Route};
1616
use crate::listener::{Bind, DefaultListener, Endpoint, Listener};
1717
use crate::router::Router;
@@ -247,7 +247,7 @@ impl Rocket<Build> {
247247
B::Error: fmt::Display,
248248
M: Fn(&Origin<'a>, T) -> T,
249249
F: Fn(&mut Self, T),
250-
T: Clone + Traceable,
250+
T: Clone + Trace,
251251
{
252252
let mut base = match base.clone().try_into() {
253253
Ok(origin) => origin.into_owned(),

core/lib/src/server.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ use crate::error::log_server_error;
1717
use crate::data::{IoStream, RawStream};
1818
use crate::util::{spawn_inspect, FutureExt, ReaderStream};
1919
use crate::http::Status;
20-
use crate::trace::{Traceable, TraceableCollection};
20+
use crate::trace::{Trace, TraceAll};
2121

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

@@ -34,6 +34,7 @@ impl Rocket<Orbit> {
3434
upgrade: Option<hyper::upgrade::OnUpgrade>,
3535
connection: ConnectionMeta,
3636
) -> Result<hyper::Response<ReaderStream<ErasedResponse>>, http::Error> {
37+
connection.trace_debug();
3738
let request = ErasedRequest::new(self, parts, |rocket, parts| {
3839
Request::from_hyp(rocket, parts, connection).unwrap_or_else(|e| e)
3940
});

core/lib/src/trace/level.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ pub fn serialize<S: Serializer>(level: &Option<Level>, s: S) -> Result<S::Ok, S:
1010
pub fn deserialize<'de, D: Deserializer<'de>>(de: D) -> Result<Option<Level>, D::Error> {
1111
struct Visitor;
1212

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

1515
impl<'de> de::Visitor<'de> for Visitor {
1616
type Value = Option<Level>;

core/lib/src/trace/mod.rs

+15-6
Original file line numberDiff line numberDiff line change
@@ -9,15 +9,24 @@ pub mod subscriber;
99
pub(crate) mod level;
1010

1111
#[doc(inline)]
12-
pub use traceable::{Traceable, TraceableCollection};
12+
pub use traceable::{Trace, TraceAll};
1313

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

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

21-
#[cfg(all(feature = "trace", not(debug_assertions)))]
22-
subscriber::RocketFmt::<subscriber::Compact>::init(_config.into());
28+
#[cfg_attr(nightly, doc(cfg(feature = "trace")))]
29+
pub fn init<'a, T: Into<Option<&'a crate::Config>>>(config: T) {
30+
#[cfg(feature = "trace")]
31+
crate::trace::subscriber::RocketDynFmt::init(config.into())
2332
}

core/lib/src/trace/subscriber/common.rs

+10-40
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,23 @@
11
use std::fmt;
22
use std::cell::Cell;
3-
use std::sync::OnceLock;
43

5-
use tracing::{Level, Metadata};
64
use tracing::field::Field;
7-
8-
use tracing_subscriber::prelude::*;
9-
use tracing_subscriber::layer::Layered;
10-
use tracing_subscriber::{reload, filter, Layer, Registry};
5+
use tracing::{Level, Metadata};
6+
use tracing_subscriber::filter;
117
use tracing_subscriber::field::RecordFields;
128

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

16-
use crate::config::{Config, CliColors};
17-
use crate::trace::subscriber::{RecordDisplay, RequestId, RequestIdLayer};
12+
use crate::config::CliColors;
13+
use crate::trace::subscriber::RecordDisplay;
1814
use crate::util::Formatter;
1915

2016
mod private {
21-
pub trait FmtKind: Default + Copy + Send + Sync + 'static { }
17+
pub trait FmtKind: Send + Sync + 'static { }
2218

23-
impl FmtKind for crate::trace::subscriber::Pretty {}
24-
impl FmtKind for crate::trace::subscriber::Compact {}
19+
impl FmtKind for crate::trace::subscriber::Pretty { }
20+
impl FmtKind for crate::trace::subscriber::Compact { }
2521
}
2622

2723
#[derive(Default)]
@@ -32,9 +28,7 @@ pub struct RocketFmt<K: private::FmtKind> {
3228
pub(crate) style: Style,
3329
}
3430

35-
pub type Handle<K> = reload::Handle<RocketFmt<K>, Layered<RequestIdLayer, Registry>>;
36-
37-
impl<K: private::FmtKind> RocketFmt<K> {
31+
impl<K: private::FmtKind + Default + Copy> RocketFmt<K> {
3832
pub(crate) fn state(&self) -> K {
3933
self.state.get_or_default().get()
4034
}
@@ -45,33 +39,9 @@ impl<K: private::FmtKind> RocketFmt<K> {
4539
update(&mut old);
4640
cell.set(old);
4741
}
42+
}
4843

49-
pub(crate) fn init_with(config: Option<&Config>, handle: &OnceLock<Handle<K>>)
50-
where Self: Layer<Layered<RequestIdLayer, Registry>>
51-
{
52-
// Do nothing if there's no config and we've already initialized.
53-
if config.is_none() && handle.get().is_some() {
54-
return;
55-
}
56-
57-
let workers = config.map(|c| c.workers).unwrap_or(num_cpus::get());
58-
let cli_colors = config.map(|c| c.cli_colors).unwrap_or(CliColors::Auto);
59-
let log_level = config.map(|c| c.log_level).unwrap_or(Some(Level::INFO));
60-
61-
let formatter = RocketFmt::new(workers, cli_colors, log_level);
62-
let (layer, reload_handle) = reload::Layer::new(formatter);
63-
let result = tracing_subscriber::registry()
64-
.with(RequestId::layer())
65-
.with(layer)
66-
.try_init();
67-
68-
if result.is_ok() {
69-
assert!(handle.set(reload_handle).is_ok());
70-
} if let Some(handle) = handle.get() {
71-
assert!(handle.modify(|layer| layer.reset(cli_colors, log_level)).is_ok());
72-
}
73-
}
74-
44+
impl<K: private::FmtKind> RocketFmt<K> {
7545
pub fn new(workers: usize, cli_colors: CliColors, level: Option<Level>) -> Self {
7646
Self {
7747
state: ThreadLocal::with_capacity(workers),

0 commit comments

Comments
 (0)