From c9f5e849732b39537aa1d382268a6938abe24e25 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Huchet?= Date: Fri, 12 May 2017 09:53:51 +0200 Subject: [PATCH] Add "Log messages in a custom format" recipe --- src/app.md | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/src/app.md b/src/app.md index 6bba227..c99cbbf 100644 --- a/src/app.md +++ b/src/app.md @@ -5,6 +5,7 @@ | [Parse command line arguments][ex-clap-basic] | [![clap-badge]][clap] | [![cat-command-line-badge]][cat-command-line] | | [Log a debug message to the console][ex-log-debug] | [![log-badge]][log] [![env_logger-badge]][env_logger] | [![cat-debugging-badge]][cat-debugging] | | [Log an error message to the console][ex-log-error] | [![log-badge]][log] [![env_logger-badge]][env_logger] | [![cat-debugging-badge]][cat-debugging] | +| [Log messages in a custom format][ex-log-custom] | [![log-badge]][log] | [![cat-debugging-badge]][cat-debugging] | | [Enable log levels per module][ex-log-mod] | [![log-badge]][log] [![env_logger-badge]][env_logger] | [![cat-debugging-badge]][cat-debugging] | | [Log to the Unix syslog][ex-log-syslog] | [![log-badge]][log] [![syslog-badge]][syslog] | [![cat-debugging-badge]][cat-debugging] | | [Log messages to a custom location][ex-log-custom] | [![log-badge]][log] | [![cat-debugging-badge]][cat-debugging] | @@ -120,6 +121,51 @@ Your favorite number must be 256. [Write me!](https://github.com/brson/rust-cookbook/issues/61) +[ex-log-custom]: #ex-log-custom + +## Log messages in a custom format + +[![log-badge]][log] [![cat-debugging-badge]][cat-debugging] + +Set a basic custom logger `ConsoleLogger` and log various messages to it. + +```rust +#[macro_use] +extern crate log; + +use log::{LogRecord, LogLevel, LogMetadata, LogLevelFilter, SetLoggerError}; + +struct ConsoleLogger; + +impl log::Log for ConsoleLogger { + fn enabled(&self, metadata: &LogMetadata) -> bool { + metadata.level() <= LogLevel::Info + } + + fn log(&self, record: &LogRecord) { + if self.enabled(record.metadata()) { + println!("Rust says: {} - {}", record.level(), record.args()); + } + } +} + +fn run() -> Result<(), SetLoggerError> { + log::set_logger(|max_log_level| { + max_log_level.set(LogLevelFilter::Info); + Box::new(ConsoleLogger) + })?; + + info!("hello log"); + warn!("warning"); + error!("oops"); + Ok(()) +} + +fn main() { + run().unwrap(); +} +``` + [ex-log-mod]: #ex-log-mod ## Enable log levels per module