Add "Log messages in a custom format" recipe

This commit is contained in:
Raphaël Huchet 2017-05-12 09:53:51 +02:00 committed by GitHub
parent 9f761b3982
commit c9f5e84973

View file

@ -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
<a name="ex-log-custom"></a>
## 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
<a name="ex-log-mod"></a>
## Enable log levels per module