日志消息

将调试消息,记录到控制台

log-badge env_logger-badge cat-debugging-badge

这个log箱子提供记录工具。这个env_logger箱子能通过环境变量,配置日志记录。这个debug!宏的工作,与其他std::fmt格式化字符串一样。

#[macro_use]
extern crate log;
extern crate env_logger;

fn execute_query(query: &str) {
    debug!("Executing query: {}", query);
}

fn main() {
    env_logger::init();

    execute_query("DROP TABLE students");
}

运行此代码时,没有输出。默认情况下,日志级别为error,任何低于此的级别,都将被删除。

设置打印消息的RUST_LOG环境变量:

$ RUST_LOG=debug cargo run

货物(cargo)打印调试信息,然后在输出的最后一行,打印以下内容:

DEBUG:main: Executing query: DROP TABLE students

将错误消息,记录到控制台

log-badge env_logger-badge cat-debugging-badge

正确的错误处理,会异常情况,视为错误。此处,log的方便宏error!,把错误日志记录到 stderr。

#[macro_use]
extern crate log;
extern crate env_logger;

fn execute_query(_query: &str) -> Result<(), &'static str> {
    Err("I'm afraid I can't do that")
}

fn main() {
    env_logger::init();

    let response = execute_query("DROP TABLE students");
    if let Err(err) = response {
        error!("Failed to execute query: {}", err);
    }
}

登录到 stdout 而不是 stderr

log-badge env_logger-badge cat-debugging-badge

使用Builder::target创建一个自定义记录器配置,将日志输出的目标设置为Target::Stdout

#[macro_use]
extern crate log;
extern crate env_logger;

use env_logger::{Builder, Target};

fn main() {
    Builder::new()
        .target(Target::Stdout)
        .init();

    error!("This error has been printed to Stdout");
}

使用自定义记录器,记录消息

log-badge cat-debugging-badge

实现一个自定义记录器ConsoleLogger,它打印到 stdout。为了使用记录的宏,ConsoleLogger实现log::Log trait,那么log::set_logger就能安装它了。

#[macro_use]
extern crate log;

use log::{Record, Level, Metadata, LevelFilter, SetLoggerError};

static CONSOLE_LOGGER: ConsoleLogger = ConsoleLogger;

struct ConsoleLogger;

impl log::Log for ConsoleLogger {
  fn enabled(&self, metadata: &Metadata) -> bool {
     metadata.level() <= Level::Info
    }

    fn log(&self, record: &Record) {
        if self.enabled(record.metadata()) {
            println!("Rust says: {} - {}", record.level(), record.args());
        }
    }

    fn flush(&self) {}
}

fn main() -> Result<(), SetLoggerError> {
    log::set_logger(&CONSOLE_LOGGER)?;
    log::set_max_level(LevelFilter::Info);

    info!("hello log");
    warn!("warning");
    error!("oops");
    Ok(())
}

登录到 Unix 系统日志

log-badge syslog-badge cat-debugging-badge

将消息记录到UNIX 系统日志。用syslog::init初始化记录器后端。 syslog::Facility表明该程序,添加的日志条目分类,log::LevelFilter表示允许的日志等级,和Option<&str>持有可选的应用程序名称。

#[macro_use]
extern crate log;
# #[cfg(target_os = "linux")]
extern crate syslog;

# #[cfg(target_os = "linux")]
use syslog::{Facility, Error};

# #[cfg(target_os = "linux")]
fn main() -> Result<(), Error> {
    syslog::init(Facility::LOG_USER,
                 log::LevelFilter::Debug,
                 Some("My app name"))?;
    debug!("this is a debug {}", "message");
    error!("this is an error!");
    Ok(())
}

# #[cfg(not(target_os = "linux"))]
# fn main() {
#     println!("So far, only Linux systems are supported.");
# }