Configure Logging

Enable log levels per module

log-badge env_logger-badge cat-debugging-badge

Creates two modules foo and nested foo::bar with logging directives controlled separately with RUST_LOG environmental variable.

extern crate log;
extern crate env_logger;

mod foo {
    mod bar {
        pub fn run() {
            warn!("[bar] warn");
            info!("[bar] info");
            debug!("[bar] debug");

    pub fn run() {
        warn!("[foo] warn");
        info!("[foo] info");
        debug!("[foo] debug");

fn main() {
    warn!("[root] warn");
    info!("[root] info");
    debug!("[root] debug");

RUST_LOG environment variable controls env_logger output. Module declarations take comma separated entries formatted like path::to::module=log_level. Run the test application as follows:

RUST_LOG="warn,test::foo=info,test::foo::bar=debug" ./test

Sets the default log::Level to warn, module foo and module foo::bar to info and debug.

WARN:test: [root] warn
WARN:test::foo: [foo] warn
INFO:test::foo: [foo] info
WARN:test::foo::bar: [bar] warn
INFO:test::foo::bar: [bar] info
DEBUG:test::foo::bar: [bar] debug

Use a custom environment variable to set up logging

log-badge env_logger-badge cat-debugging-badge

Builder configures logging.

Builder::parse parses MY_APP_LOG environment variable contents in the form of RUST_LOG syntax. Then, Builder::init initializes the logger. All these steps are normally done internally by env_logger::init.

extern crate log;
extern crate env_logger;

use std::env;
use env_logger::Builder;

fn main() {

    info!("informational message");
    warn!("warning message");
    error!("this is an error {}", "message");

Include timestamp in log messages

log-badge env_logger-badge chrono-badge cat-debugging-badge

Creates a custom logger configuration with Builder. Each log entry calls Local::now to get the current DateTime in local timezone and uses DateTime::format with strftime::specifiers to format a timestamp used in the final log.

The example calls Builder::format to set a closure which formats each message text with timestamp, Record::level and body (Record::args).

extern crate log;
extern crate chrono;
extern crate env_logger;

use std::io::Write;
use chrono::Local;
use env_logger::Builder;
use log::LevelFilter;

fn main() {
        .format(|buf, record| {
                "{} [{}] - {}",
        .filter(None, LevelFilter::Info)


stderr output will contain

2017-05-22T21:57:06 [WARN] - warn
2017-05-22T21:57:06 [INFO] - info

Log messages to a custom location

log-badge log4rs-badge cat-debugging-badge

log4rs configures log output to a custom location. log4rs can use either an external YAML file or a builder configuration.

Create the log configuration with log4rs::append::file::FileAppender. An appender defines the logging destination. The configuration continues with encoding using a custom pattern from log4rs::encode::pattern. Assigns the configuration to log4rs::config::Config and sets the default log::LevelFilter.

# #[macro_use]
# extern crate error_chain;
extern crate log;
extern crate log4rs;

use log::LevelFilter;
use log4rs::append::file::FileAppender;
use log4rs::encode::pattern::PatternEncoder;
use log4rs::config::{Appender, Config, Root};
# error_chain! {
#     foreign_links {
#         Io(std::io::Error);
#         LogConfig(log4rs::config::Errors);
#         SetLogger(log::SetLoggerError);
#     }
# }

fn run() -> Result<()> {
    let logfile = FileAppender::builder()
        .encoder(Box::new(PatternEncoder::new("{l} - {m}\n")))

    let config = Config::builder()
        .appender(Appender::builder().build("logfile", Box::new(logfile)))


    info!("Hello, world!");

# quick_main!(run);