Skip to content

Commit ced793e

Browse files
committed
refactor: move format/with_format from builder to formatter
1 parent b8ecedc commit ced793e

File tree

4 files changed

+78
-78
lines changed

4 files changed

+78
-78
lines changed

examples/custom_format.rs

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -19,17 +19,17 @@ If you want to control the logging output completely, see the `custom_logger` ex
1919

2020
#[cfg(all(feature = "color", feature = "humantime"))]
2121
fn main() {
22-
use env_logger::{Builder, Env};
22+
use env_logger::{fmt::Formatter, Env, Logger};
23+
use log::Record;
2324

2425
use std::io::Write;
2526

2627
fn init_logger() {
2728
let env = Env::default()
2829
.filter("MY_LOG_LEVEL")
2930
.write_style("MY_LOG_STYLE");
30-
31-
Builder::from_env(env)
32-
.format(|buf, record| {
31+
Logger::from_env(env)
32+
.with_format(Box::new(|buf: &mut Formatter, record: &Record<'_>| {
3333
// We are reusing `anstyle` but there are `anstyle-*` crates to adapt it to your
3434
// preferred styling crate.
3535
let warn_style = buf.default_level_style(log::Level::Warn);
@@ -40,8 +40,9 @@ fn main() {
4040
"My formatted log ({timestamp}): {warn_style}{}{warn_style:#}",
4141
record.args()
4242
)
43-
})
44-
.init();
43+
}))
44+
.try_init()
45+
.unwrap();
4546
}
4647

4748
init_logger();

examples/syslog_friendly_format.rs

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,12 @@
11
use std::io::Write;
22

3+
use env_logger::fmt::Formatter;
4+
use log::Record;
5+
36
fn main() {
47
match std::env::var("RUST_LOG_STYLE") {
5-
Ok(s) if s == "SYSTEMD" => env_logger::builder()
6-
.format(|buf, record| {
8+
Ok(s) if s == "SYSTEMD" => env_logger::Logger::from_default_env()
9+
.with_format(Box::new(|buf: &mut Formatter, record: &Record<'_>| {
710
writeln!(
811
buf,
912
"<{}>{}: {}",
@@ -17,8 +20,9 @@ fn main() {
1720
record.target(),
1821
record.args()
1922
)
20-
})
21-
.init(),
23+
}))
24+
.try_init()
25+
.unwrap(),
2226
_ => env_logger::init(),
2327
};
2428
}

src/fmt/mod.rs

Lines changed: 6 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
//!
88
//! # Formatting log records
99
//!
10-
//! The format used to print log records can be customised using the [`Builder::format`]
10+
//! The format used to print log records can be customised using the [`crate::Logger::with_format`]
1111
//! method.
1212
//!
1313
//! Terminal styling is done through ANSI escape codes and will be adapted to the capabilities of
@@ -53,7 +53,7 @@
5353
//!
5454
//! See <https://docs.rs/log/latest/log/#structured-logging>.
5555
//!
56-
//! [`Builder::format`]: crate::Builder::format
56+
//! [`Logger::with_fmt`]: crate::Logger::with_fmt
5757
//! [`Write`]: std::io::Write
5858
//! [`Builder::format_key_values`]: crate::Builder::format_key_values
5959
@@ -200,7 +200,7 @@ impl fmt::Debug for Formatter {
200200
}
201201
}
202202

203-
pub(crate) trait RecordFormat {
203+
pub trait RecordFormat {
204204
fn format(&self, formatter: &mut Formatter, record: &Record<'_>) -> io::Result<()>;
205205
}
206206

@@ -217,8 +217,7 @@ pub(crate) type FormatFn = Box<dyn RecordFormat + Sync + Send>;
217217

218218
#[derive(Default)]
219219
pub(crate) struct Builder {
220-
pub(crate) default_format: ConfigurableFormat,
221-
pub(crate) custom_format: Option<FormatFn>,
220+
pub(crate) format: ConfigurableFormat,
222221
built: bool,
223222
}
224223

@@ -239,11 +238,7 @@ impl Builder {
239238
},
240239
);
241240

242-
if let Some(fmt) = built.custom_format {
243-
fmt
244-
} else {
245-
Box::new(built.default_format)
246-
}
241+
Box::new(built.format)
247242
}
248243
}
249244

@@ -276,7 +271,7 @@ impl<T: Display> Display for StyledValue<T> {
276271
#[cfg(not(feature = "color"))]
277272
type StyledValue<T> = T;
278273

279-
/// A [custom format][crate::Builder::format] with settings for which fields to show
274+
/// A custom format with settings for which fields to show
280275
pub struct ConfigurableFormat {
281276
// This format needs to work with any combination of crate features.
282277
pub(crate) timestamp: Option<TimestampPrecision>,

src/logger.rs

Lines changed: 57 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use std::{borrow::Cow, cell::RefCell, env, io};
1+
use std::{borrow::Cow, cell::RefCell, env};
22

33
use log::{LevelFilter, Log, Metadata, Record, SetLoggerError};
44

@@ -211,43 +211,6 @@ impl Builder {
211211
self.parse_env(Env::default())
212212
}
213213

214-
/// Sets the format function for formatting the log output.
215-
///
216-
/// This function is called on each record logged and should format the
217-
/// log record and output it to the given [`Formatter`].
218-
///
219-
/// The format function is expected to output the string directly to the
220-
/// `Formatter` so that implementations can use the [`std::fmt`] macros
221-
/// to format and output without intermediate heap allocations. The default
222-
/// `env_logger` formatter takes advantage of this.
223-
///
224-
/// When the `color` feature is enabled, styling via ANSI escape codes is supported and the
225-
/// output will automatically respect [`Builder::write_style`].
226-
///
227-
/// # Examples
228-
///
229-
/// Use a custom format to write only the log message:
230-
///
231-
/// ```
232-
/// use std::io::Write;
233-
/// use env_logger::Builder;
234-
///
235-
/// let mut builder = Builder::new();
236-
///
237-
/// builder.format(|buf, record| writeln!(buf, "{}", record.args()));
238-
/// ```
239-
///
240-
/// [`Formatter`]: fmt/struct.Formatter.html
241-
/// [`String`]: https://doc.rust-lang.org/stable/std/string/struct.String.html
242-
/// [`std::fmt`]: https://doc.rust-lang.org/std/fmt/index.html
243-
pub fn format<F>(&mut self, format: F) -> &mut Self
244-
where
245-
F: Fn(&mut Formatter, &Record<'_>) -> io::Result<()> + Sync + Send + 'static,
246-
{
247-
self.format.custom_format = Some(Box::new(format));
248-
self
249-
}
250-
251214
/// Use the default format.
252215
///
253216
/// This method will clear any custom format set on the builder.
@@ -258,21 +221,21 @@ impl Builder {
258221

259222
/// Whether or not to write the level in the default format.
260223
pub fn format_level(&mut self, write: bool) -> &mut Self {
261-
self.format.default_format.level(write);
224+
self.format.format.level(write);
262225
self
263226
}
264227

265228
/// Whether or not to write the source file path in the default format.
266229
pub fn format_file(&mut self, write: bool) -> &mut Self {
267-
self.format.default_format.file(write);
230+
self.format.format.file(write);
268231
self
269232
}
270233

271234
/// Whether or not to write the source line number path in the default format.
272235
///
273236
/// Only has effect if `format_file` is also enabled
274237
pub fn format_line_number(&mut self, write: bool) -> &mut Self {
275-
self.format.default_format.line_number(write);
238+
self.format.format.line_number(write);
276239
self
277240
}
278241

@@ -287,26 +250,26 @@ impl Builder {
287250

288251
/// Whether or not to write the module path in the default format.
289252
pub fn format_module_path(&mut self, write: bool) -> &mut Self {
290-
self.format.default_format.module_path(write);
253+
self.format.format.module_path(write);
291254
self
292255
}
293256

294257
/// Whether or not to write the target in the default format.
295258
pub fn format_target(&mut self, write: bool) -> &mut Self {
296-
self.format.default_format.target(write);
259+
self.format.format.target(write);
297260
self
298261
}
299262

300263
/// Configures the amount of spaces to use to indent multiline log records.
301264
/// A value of `None` disables any kind of indentation.
302265
pub fn format_indent(&mut self, indent: Option<usize>) -> &mut Self {
303-
self.format.default_format.indent(indent);
266+
self.format.format.indent(indent);
304267
self
305268
}
306269

307270
/// Configures if timestamp should be included and in what precision.
308271
pub fn format_timestamp(&mut self, timestamp: Option<fmt::TimestampPrecision>) -> &mut Self {
309-
self.format.default_format.timestamp(timestamp);
272+
self.format.format.timestamp(timestamp);
310273
self
311274
}
312275

@@ -332,7 +295,7 @@ impl Builder {
332295

333296
/// Configures the end of line suffix.
334297
pub fn format_suffix(&mut self, suffix: &'static str) -> &mut Self {
335-
self.format.default_format.suffix(suffix);
298+
self.format.format.suffix(suffix);
336299
self
337300
}
338301

@@ -349,9 +312,9 @@ impl Builder {
349312
#[cfg(feature = "kv")]
350313
pub fn format_key_values<F>(&mut self, format: F) -> &mut Self
351314
where
352-
F: Fn(&mut Formatter, &dyn log::kv::Source) -> io::Result<()> + Sync + Send + 'static,
315+
F: Fn(&mut Formatter, &dyn log::kv::Source) -> std::io::Result<()> + Sync + Send + 'static,
353316
{
354-
self.format.default_format.key_values(format);
317+
self.format.format.key_values(format);
355318
self
356319
}
357320

@@ -497,15 +460,7 @@ impl Builder {
497460
/// library has already initialized a global logger.
498461
pub fn try_init(&mut self) -> Result<(), SetLoggerError> {
499462
let logger = self.build();
500-
501-
let max_level = logger.filter();
502-
let r = log::set_boxed_logger(Box::new(logger));
503-
504-
if r.is_ok() {
505-
log::set_max_level(max_level);
506-
}
507-
508-
r
463+
logger.try_init()
509464
}
510465

511466
/// Initializes the global logger with the built env logger.
@@ -641,6 +596,51 @@ impl Logger {
641596
pub fn matches(&self, record: &Record<'_>) -> bool {
642597
self.filter.matches(record)
643598
}
599+
600+
/// Sets the format function for formatting the log output.
601+
///
602+
/// This function is called on each record logged and should format the
603+
/// log record and output it to the given [`Formatter`].
604+
///
605+
/// The format function is expected to output the string directly to the
606+
/// `Formatter` so that implementations can use the [`std::fmt`] macros
607+
/// to format and output without intermediate heap allocations. The default
608+
/// `env_logger` formatter takes advantage of this.
609+
///
610+
/// When the `color` feature is enabled, styling via ANSI escape codes is supported and the
611+
/// output will automatically respect [`Builder::write_style`].
612+
///
613+
/// # Examples
614+
///
615+
/// Use a custom format to write only the log message:
616+
///
617+
/// ```
618+
/// use std::io::Write;
619+
/// use env_logger::Builder;
620+
///
621+
/// let mut builder = Builder::new();
622+
///
623+
/// builder.format(|buf, record| writeln!(buf, "{}", record.args()));
624+
/// ```
625+
///
626+
/// [`Formatter`]: fmt/struct.Formatter.html
627+
/// [`String`]: https://doc.rust-lang.org/stable/std/string/struct.String.html
628+
/// [`std::fmt`]: https://doc.rust-lang.org/std/fmt/index.html
629+
pub fn with_format(mut self, format: FormatFn) -> Self {
630+
self.format = format;
631+
self
632+
}
633+
634+
pub fn try_init(self) -> Result<(), SetLoggerError> {
635+
let max_level = self.filter();
636+
let r = log::set_boxed_logger(Box::new(self));
637+
638+
if r.is_ok() {
639+
log::set_max_level(max_level);
640+
}
641+
642+
r
643+
}
644644
}
645645

646646
impl Log for Logger {

0 commit comments

Comments
 (0)