Skip to content
This repository was archived by the owner on Nov 15, 2023. It is now read-only.

Commit 06dedb0

Browse files
authored
Make init_logging more easily usable (#6620)
Instead of requiring the `LogRotationOpt`, it now requires an `Option<LogRotationOpt>`. This makes it much more easy to use the interface when someone isn't interested on the `LogRotationOpt`'s
1 parent efbac7b commit 06dedb0

File tree

3 files changed

+81
-83
lines changed

3 files changed

+81
-83
lines changed

bin/node/bench/src/main.rs

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -63,9 +63,6 @@ struct Opt {
6363
#[structopt(long)]
6464
transactions: Option<usize>,
6565

66-
#[structopt(flatten)]
67-
log_rotation_opt: sc_cli::LogRotationOpt,
68-
6966
/// Mode
7067
///
7168
/// "regular" for regular benchmark
@@ -80,7 +77,7 @@ fn main() {
8077
let opt = Opt::from_args();
8178

8279
if !opt.json {
83-
sc_cli::init_logger("", &opt.log_rotation_opt).expect("init_logger should not fail.");
80+
sc_cli::init_logger("", None).expect("init_logger should not fail.");
8481
}
8582

8683
let mut import_benchmarks = Vec::new();

client/cli/src/config.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -490,10 +490,10 @@ pub trait CliConfiguration: Sized {
490490
}
491491

492492
/// Get the log directory for logging.
493-
///
493+
///
494494
/// By default this is retrieved from `SharedParams`.
495-
fn log_rotation_opt(&self) -> Result<&LogRotationOpt> {
496-
Ok(self.shared_params().log_rotation_opt())
495+
fn log_rotation_opt(&self) -> Result<LogRotationOpt> {
496+
Ok(self.shared_params().log_rotation_opt().clone())
497497
}
498498

499499
/// Initialize substrate. This must be done only once.
@@ -510,7 +510,7 @@ pub trait CliConfiguration: Sized {
510510
sp_panic_handler::set(&C::support_url(), &C::impl_version());
511511

512512
fdlimit::raise_fd_limit();
513-
init_logger(&logger_pattern, log_rotation_opt)?;
513+
init_logger(&logger_pattern, Some(log_rotation_opt))?;
514514

515515
Ok(())
516516
}

client/cli/src/logger.rs

Lines changed: 76 additions & 75 deletions
Original file line numberDiff line numberDiff line change
@@ -18,15 +18,13 @@
1818

1919
use ansi_term::Colour;
2020
use flexi_logger::{
21-
DeferredNow, Duplicate, LogSpecBuilder,
22-
LogSpecification, LogTarget, Logger, Criterion, Naming, Cleanup, Age,
21+
DeferredNow, Duplicate, LogSpecBuilder,
22+
LogSpecification, LogTarget, Logger, Criterion, Naming, Cleanup, Age,
2323
};
2424
use lazy_static::lazy_static;
2525
use regex::Regex;
2626
use std::path::PathBuf;
27-
use structopt::{
28-
StructOpt,
29-
};
27+
use structopt::StructOpt;
3028
use crate::error::{Error, Result};
3129

3230
type IoResult = std::result::Result<(), std::io::Error>;
@@ -35,18 +33,18 @@ type IoResult = std::result::Result<(), std::io::Error>;
3533
const DEFAULT_ROTATION_SIZE: u64 = u64::MAX;
3634

3735
/// Options for log rotation.
38-
#[derive(Debug, StructOpt)]
36+
#[derive(Debug, StructOpt, Default, Clone)]
3937
pub struct LogRotationOpt {
4038
/// Specify the path of the directory which will contain the log files.
4139
/// Defaults to never rotating logs.
4240
#[structopt(long, parse(from_os_str))]
4341
log_directory: Option<PathBuf>,
44-
42+
4543
/// Rotate the log file when the local clock has started a new day/hour/minute/second
4644
/// since the current file has been created.
4745
#[structopt(long,
48-
conflicts_with("log-size"),
49-
possible_values(&["day", "hour", "minute", "second"]),
46+
conflicts_with("log-size"),
47+
possible_values(&["day", "hour", "minute", "second"]),
5048
parse(from_str = age_from_str))
5149
]
5250
log_age: Option<Age>,
@@ -58,90 +56,92 @@ pub struct LogRotationOpt {
5856

5957
/// Utility for parsing an Age from a &str.
6058
fn age_from_str(s: &str) -> Age {
61-
match s {
62-
"day" => Age::Day,
63-
"hour" => Age::Hour,
64-
"minute" => Age::Minute,
65-
"second" => Age::Second,
66-
_ => unreachable!(),
59+
match s {
60+
"day" => Age::Day,
61+
"hour" => Age::Hour,
62+
"minute" => Age::Minute,
63+
"second" => Age::Second,
64+
_ => unreachable!(),
6765
}
6866
}
6967

7068
/// Format used when writing to a tty. Colors the output.
7169
fn colored_fmt(
72-
w: &mut dyn std::io::Write,
73-
_now: &mut DeferredNow,
74-
record: &log::Record,
70+
w: &mut dyn std::io::Write,
71+
_now: &mut DeferredNow,
72+
record: &log::Record,
7573
) -> IoResult {
76-
let now = time::now();
77-
let timestamp =
78-
time::strftime("%Y-%m-%d %H:%M:%S", &now).expect("Error formatting log timestamp");
79-
80-
let output = if log::max_level() <= log::LevelFilter::Info {
81-
format!(
82-
"{} {}",
83-
Colour::Black.bold().paint(timestamp),
84-
record.args(),
85-
)
86-
} else {
87-
let name = ::std::thread::current()
88-
.name()
89-
.map_or_else(Default::default, |x| {
90-
format!("{}", Colour::Blue.bold().paint(x))
91-
});
92-
let millis = (now.tm_nsec as f32 / 1000000.0).floor() as usize;
93-
let timestamp = format!("{}.{:03}", timestamp, millis);
94-
format!(
95-
"{} {} {} {} {}",
96-
Colour::Black.bold().paint(timestamp),
97-
name,
98-
record.level(),
99-
record.target(),
100-
record.args()
101-
)
102-
};
103-
104-
write!(w, "{}", output)
74+
let now = time::now();
75+
let timestamp =
76+
time::strftime("%Y-%m-%d %H:%M:%S", &now).expect("Error formatting log timestamp");
77+
78+
let output = if log::max_level() <= log::LevelFilter::Info {
79+
format!(
80+
"{} {}",
81+
Colour::Black.bold().paint(timestamp),
82+
record.args(),
83+
)
84+
} else {
85+
let name = ::std::thread::current()
86+
.name()
87+
.map_or_else(Default::default, |x| {
88+
format!("{}", Colour::Blue.bold().paint(x))
89+
});
90+
let millis = (now.tm_nsec as f32 / 1000000.0).floor() as usize;
91+
let timestamp = format!("{}.{:03}", timestamp, millis);
92+
format!(
93+
"{} {} {} {} {}",
94+
Colour::Black.bold().paint(timestamp),
95+
name,
96+
record.level(),
97+
record.target(),
98+
record.args()
99+
)
100+
};
101+
102+
write!(w, "{}", output)
105103
}
106104

107105
/// Format used when logging to files. Does not add any colors.
108106
fn file_fmt(
109-
w: &mut dyn std::io::Write,
110-
_now: &mut DeferredNow,
111-
record: &log::Record,
107+
w: &mut dyn std::io::Write,
108+
_now: &mut DeferredNow,
109+
record: &log::Record,
112110
) -> IoResult {
113-
let now = time::now();
114-
let timestamp =
115-
time::strftime("%Y-%m-%d %H:%M:%S", &now).expect("Error formatting log timestamp");
116-
117-
let output = if log::max_level() <= log::LevelFilter::Info {
118-
format!("{} {}", timestamp, record.args(),)
119-
} else {
120-
let name = std::thread::current()
121-
.name()
122-
.map_or_else(Default::default, |x| format!("{}", x));
123-
let millis = (now.tm_nsec as f32 / 1000000.0).floor() as usize;
124-
let timestamp = format!("{}.{:03}", timestamp, millis);
125-
format!(
126-
"{} {} {} {} {}",
127-
timestamp,
128-
name,
129-
record.level(),
130-
record.target(),
131-
record.args()
132-
)
111+
let now = time::now();
112+
let timestamp =
113+
time::strftime("%Y-%m-%d %H:%M:%S", &now).expect("Error formatting log timestamp");
114+
115+
let output = if log::max_level() <= log::LevelFilter::Info {
116+
format!("{} {}", timestamp, record.args(),)
117+
} else {
118+
let name = std::thread::current()
119+
.name()
120+
.map_or_else(Default::default, |x| format!("{}", x));
121+
let millis = (now.tm_nsec as f32 / 1000000.0).floor() as usize;
122+
let timestamp = format!("{}.{:03}", timestamp, millis);
123+
format!(
124+
"{} {} {} {} {}",
125+
timestamp,
126+
name,
127+
record.level(),
128+
record.target(),
129+
record.args()
130+
)
133131
};
134132

135133
// Required because substrate sometimes sends strings that are colored.
136134
// Doing this ensures no colors are ever printed to files.
137135
let output = kill_color(&output);
138136

139-
write!(w, "{}", output)
137+
write!(w, "{}", output)
140138
}
141139

142140
/// Initialize the logger
143-
pub fn init_logger(pattern: &str, log_rotation_opt: &LogRotationOpt) -> Result<()> {
144-
141+
pub fn init_logger(
142+
pattern: &str,
143+
log_rotation_opt: Option<LogRotationOpt>,
144+
) -> Result<()> {
145145
let mut builder = LogSpecBuilder::new();
146146
// Disable info logging by default for some modules:
147147
builder.module("ws", log::LevelFilter::Off);
@@ -167,6 +167,7 @@ pub fn init_logger(pattern: &str, log_rotation_opt: &LogRotationOpt) -> Result<(
167167
// Never cleanup old logs; let the end-user take care of that.
168168
let cleanup = Cleanup::Never;
169169

170+
let log_rotation_opt = log_rotation_opt.unwrap_or_default();
170171
let age = log_rotation_opt.log_age;
171172
let size = log_rotation_opt.log_size;
172173

@@ -254,7 +255,7 @@ mod tests {
254255
log_size: None,
255256
};
256257

257-
assert!(init_logger(pattern, &log_rotation_opt).is_ok());
258+
assert!(init_logger(pattern, Some(log_rotation_opt)).is_ok());
258259
}
259260

260261
#[test]
@@ -266,6 +267,6 @@ mod tests {
266267
log_size: Some(1337),
267268
};
268269

269-
assert!(init_logger(pattern, &log_rotation_opt).is_err());
270+
assert!(init_logger(pattern, Some(log_rotation_opt)).is_err());
270271
}
271272
}

0 commit comments

Comments
 (0)