Skip to content

Commit

Permalink
Improve documentation of pattern macro and Pattern trait
Browse files Browse the repository at this point in the history
Co-Authored-By: Sirui Mu <msrlancern@gmail.com>
  • Loading branch information
SpriteOvO and Lancern committed Sep 18, 2022
1 parent 4c38cee commit 0cafb39
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 117 deletions.
163 changes: 50 additions & 113 deletions spdlog/src/formatter/pattern_formatter/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@ use crate::{
Error, Record, StringBuf,
};

/// Build a pattern from a compile-time pattern template string.
/// Build a pattern from a template string at compile-time.
///
/// It accepts input of the similar form:
/// It accepts inputs in the form:
///
/// ```ignore
/// // This is not exactly a valid declarative macro, just for intuition.
Expand Down Expand Up @@ -51,42 +51,29 @@ use crate::{
/// ```
/// use spdlog::formatter::{pattern, PatternFormatter};
///
/// let pat = pattern!("pattern string");
/// let formatter = PatternFormatter::new(pat);
/// let formatter = PatternFormatter::new(pattern!("pattern string"));
/// ```
///
/// # Using spdlog Built-in Patterns
/// # Using Built-in Placeholders
///
/// A pattern that always outputs a fixed string is boring and useless.
/// Luckily, the pattern template string can contain placeholders that
/// represents built-in patterns. For example, to include the log level and
/// payload in the pattern, we can simply use `{l}` and `{v}` in the pattern
/// template string:
/// payload in the pattern, we can simply use `{level}` and `{payload}` in the
/// pattern template string:
/// ```
/// # use spdlog::formatter::{pattern, PatternFormatter};
/// use spdlog::info;
///
/// let pat = pattern!("[{level}] {payload}");
/// let formatter = PatternFormatter::new(pat);
/// let formatter = PatternFormatter::new(pattern!("[{level}] {payload}"));
///
/// info!("Interesting log message");
/// // Logs: [info] Interesting log message
/// ```
///
/// Here, `{l}` and `{v}` are "placeholders" that will be replaced by the
/// output of the corresponding built-in patterns when formatting log records.
/// You can also use `{level}` and `{payload}`, if you prefer:
/// ```
/// # use spdlog::{
/// # formatter::{pattern, PatternFormatter},
/// # info,
/// # };
/// let pat = pattern!("[{level}] {payload}");
/// let formatter = PatternFormatter::new(pat);
///
/// info!("Interesting log message");
/// // Logs: [info] Interesting log message
/// ```
/// Here, `{level}` and `{payload}` are "placeholders" that will be replaced by
/// the output of the corresponding built-in patterns when formatting log
/// records.
///
/// What if you want to output a literal `{` or `}` character? Simply use `{{`
/// and `}}`:
Expand All @@ -95,15 +82,15 @@ use crate::{
/// # formatter::{pattern, PatternFormatter},
/// # info,
/// # };
/// let pat = pattern!("[{{level}}] {payload}");
/// let formatter = PatternFormatter::new(pat);
/// let formatter = PatternFormatter::new(pattern!("[{{escaped}}] {payload}"));
///
/// info!("Interesting log message");
/// // Logs: [{level}] Interesting log message
/// // Logs: [{escaped}] Interesting log message
/// ```
///
/// You can find a full list of all built-in patterns and their corresponding
/// placeholders at the end of this doc page.
/// placeholders at [Appendix](#appendix-a-full-list-of-built-in-placeholders)
/// below.
///
/// # Using Style Range
///
Expand All @@ -116,8 +103,7 @@ use crate::{
/// # formatter::{pattern, PatternFormatter},
/// # info,
/// # };
/// let pat = pattern!("{^[{level}]} {payload}");
/// let formatter = PatternFormatter::new(pat);
/// let formatter = PatternFormatter::new(pattern!("{^[{level}]} {payload}"));
///
/// info!("Interesting log message");
/// // Logs: [info] Interesting log message
Expand All @@ -131,8 +117,11 @@ use crate::{
/// [`Pattern`] trait:
/// ```
/// use std::fmt::Write;
/// use spdlog::{Record, StringBuf};
/// use spdlog::formatter::{Pattern, PatternContext};
///
/// use spdlog::{
/// formatter::{Pattern, PatternContext},
/// Record, StringBuf,
/// };
///
/// #[derive(Default)]
/// struct MyPattern;
Expand All @@ -155,8 +144,11 @@ use crate::{
/// can resolve it:
/// ```
/// # use std::fmt::Write;
/// # use spdlog::{info, Record, StringBuf};
/// # use spdlog::formatter::{pattern, Pattern, PatternContext, PatternFormatter};
/// # use spdlog::{
/// # formatter::{pattern, Pattern, PatternContext, PatternFormatter},
/// # prelude::*,
/// # Record, StringBuf,
/// # };
/// #
/// # #[derive(Default)]
/// # struct MyPattern;
Expand Down Expand Up @@ -194,12 +186,20 @@ use crate::{
/// ## Custom Pattern Creation
///
/// Each placeholder results in a new pattern instance. For example, consider a
/// custom pattern that writes a unique ID to the output:
/// custom pattern that writes a unique ID to the output. If the pattern
/// template string contains multiple placeholders that refer to `MyPattern`,
/// each placeholder will eventually be replaced by different IDs.
///
/// ```
/// # use std::fmt::Write;
/// # use std::sync::atomic::{AtomicU32, Ordering};
/// # use spdlog::{Record, StringBuf};
/// # use spdlog::formatter::{Pattern, PatternContext};
/// # use std::{
/// # fmt::Write,
/// # sync::atomic::{AtomicU32, Ordering},
/// # };
/// # use spdlog::{
/// # formatter::{pattern, Pattern, PatternContext, PatternFormatter},
/// # prelude::*,
/// # Record, StringBuf,
/// # };
/// #
/// static NEXT_ID: AtomicU32 = AtomicU32::new(0);
///
Expand All @@ -226,43 +226,7 @@ use crate::{
/// Ok(())
/// }
/// }
/// ```
///
/// If the pattern template string contains multiple placeholders that refer
/// to `MyPattern`, each placeholder will eventually be replaced by different
/// IDs:
/// ```
/// # use std::fmt::Write;
/// # use std::sync::atomic::{AtomicU32, Ordering};
/// # use spdlog::{info, Record, StringBuf};
/// # use spdlog::formatter::{pattern, Pattern, PatternContext, PatternFormatter};
/// #
/// # static NEXT_ID: AtomicU32 = AtomicU32::new(0);
/// #
/// # struct MyPattern {
/// # id: u32,
/// # }
/// #
/// # impl MyPattern {
/// # fn new() -> Self {
/// # Self {
/// # id: NEXT_ID.fetch_add(1, Ordering::Relaxed),
/// # }
/// # }
/// # }
/// #
/// # impl Pattern for MyPattern {
/// # fn format(
/// # &self,
/// # record: &Record,
/// # dest: &mut StringBuf,
/// # _ctx: &mut PatternContext,
/// # ) -> spdlog::Result<()> {
/// # write!(dest, "{}", self.id).unwrap();
/// # Ok(())
/// # }
/// # }
/// #
/// let pat = pattern!("[{level}] {payload} - {$mypat} {$mypat} {$mypat}",
/// {$mypat} => MyPattern::new,
/// );
Expand All @@ -274,53 +238,26 @@ use crate::{
///
/// Of course, you can have multiple custom patterns:
/// ```
/// # use std::fmt::Write;
/// # use spdlog::{Record, StringBuf};
/// # use spdlog::formatter::{pattern, Pattern, PatternContext, PatternFormatter};
/// # use spdlog::formatter::pattern;
/// #
/// # #[derive(Default)]
/// # struct MyPattern;
/// #
/// # impl Pattern for MyPattern {
/// # fn format(
/// # &self,
/// # record: &Record,
/// # dest: &mut StringBuf,
/// # _ctx: &mut PatternContext,
/// # ) -> spdlog::Result<()> {
/// # write!(dest, "My own pattern").unwrap();
/// # Ok(())
/// # }
/// # }
/// #
/// # #[derive(Default)]
/// # struct MyOtherPattern;
/// #
/// # impl Pattern for MyOtherPattern {
/// # fn format(
/// # &self,
/// # record: &Record,
/// # dest: &mut StringBuf,
/// # _ctx: &mut PatternContext,
/// # ) -> spdlog::Result<()> {
/// # write!(dest, "My own pattern").unwrap();
/// # Ok(())
/// # }
/// # }
/// #
/// let pat = pattern!("[{level}] {payload} - {$mypat} {$mypat2}",
/// let pat = pattern!("[{level}] {payload} - {$mypat} {$myotherpat}",
/// {$mypat} => MyPattern::default,
/// {$mypat2} => MyOtherPattern::default,
/// {$myotherpat} => MyOtherPattern::default,
/// );
/// let formatter = PatternFormatter::new(pat);
/// ```
///
/// ## Name Conflicts are Hard Errors
///
/// It's a hard error if names of your own custom pattern conflicts with other
/// patterns:
///
/// ```compile_fail
/// # use spdlog::{formatter::Pattern, pattern};
/// # use spdlog::formatter::pattern;
/// #
/// # #[derive(Default)]
/// # struct MyPattern;
Expand All @@ -333,8 +270,9 @@ use crate::{
/// {$mypat} => MyOtherPattern::new,
/// );
/// ```
///
/// ```compile_fail
/// # use spdlog::{formatter::Pattern, pattern};
/// # use spdlog::formatter::pattern;
/// #
/// # #[derive(Default)]
/// # struct MyPattern;
Expand All @@ -345,7 +283,7 @@ use crate::{
/// );
/// ```
///
/// # Appendix: A Full List of Built-in Patterns and Their Placeholders
/// # Appendix: A Full List of Built-in Placeholders
///
/// | Placeholders | Description | Example |
/// | --- | --- | --- |
Expand Down Expand Up @@ -461,15 +399,14 @@ impl PatternContext {
///
/// # Custom Patterns
///
/// There are 2 approaches to create your own pattern:
/// - Define a new type and implements this trait;
/// - Use the [`pattern`] macro to create a pattern from a template string.
/// You can define a new type and implement this trait to create your own
/// pattern.
pub trait Pattern: Send + Sync {
/// Format this pattern against the given log record and write the formatted
/// message into the output buffer.
///
/// **For implementors:** the `ctx` parameter is reserved for internal use.
/// You should not use it.
/// **For implementors:** the `ctx` parameter is reserved for future use.
/// For now, please ignore it.
fn format(
&self,
record: &Record,
Expand Down
4 changes: 0 additions & 4 deletions spdlog/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -152,10 +152,6 @@
//!
//! - `spdlog-rs` does not have `backtrace`[^2].
//!
//! - `spdlog-rs` currently does not have `pattern_formatter`. The solution for
//! custom formatting log messages is to implement your own [`Formatter`]
//! structure and then call [`Sink::set_formatter`].
//!
//! - In `spdlog-rs`, [`LevelFilter`] is a more flexible and readable enum with
//! logical conditions.
//!
Expand Down

0 comments on commit 0cafb39

Please sign in to comment.