mirror of
https://github.com/rust-lang-nursery/rust-cookbook
synced 2024-11-22 19:43:06 +00:00
Add "Log messages in a custom format" recipe
This commit is contained in:
parent
9f761b3982
commit
c9f5e84973
1 changed files with 46 additions and 0 deletions
46
src/app.md
46
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
|
||||
<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
|
||||
|
|
Loading…
Reference in a new issue