Trait ftlog::FtLogFormat

source ·
pub trait FtLogFormat: Send + Sync {
    // Required method
    fn msg(&self, record: &Record<'_>) -> Box<dyn Send + Sync + Display>;
}
Expand description

Shared by ftlog formatter

To further reduce time spent on log macro calls, ftlog saves required data and later construct log string in log thread.

FtLogFormat defines how to turn an reference to record into a box object, which can be sent to log thread and later formatted into string.

Here is an example of custom formatter:

use std::fmt::Display;

use ftlog::FtLogFormat;
use log::{Level, Record};

struct MyFormatter;
impl FtLogFormat for MyFormatter {
    fn msg(&self, record: &Record) -> Box<dyn Send + Sync + Display> {
        Box::new(Msg {
            level: record.level(),
            thread: std::thread::current().name().map(|n| n.to_string()),
            file: record.file_static(),
            line: record.line(),
            args: format!("{}", record.args()),
            module_path: record.module_path_static(),
        })
    }
}
// Store necessary field, define how to format into string with `Display` trait.
struct Msg {
    level: Level,
    thread: Option<String>,
    file: Option<&'static str>,
    line: Option<u32>,
    args: String,
    module_path: Option<&'static str>,
}

impl Display for Msg {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&format!(
            "{}@{}||{}:{}[{}] {}",
            self.thread.as_ref().map(|x| x.as_str()).unwrap_or(""),
            self.module_path.unwrap_or(""),
            self.file.unwrap_or(""),
            self.line.unwrap_or(0),
            self.level,
            self.args
        ))
    }
}

Required Methods§

source

fn msg(&self, record: &Record<'_>) -> Box<dyn Send + Sync + Display>

turn an reference to record into a box object, which can be sent to log thread and then formatted into string.

Implementors§