[][src]Crate stderrlog

A simple logger to provide symantics similar to what is expected of most UNIX utilities by logging to stderr and the higher the verbosity the higher the log level. It supports the ability to provide timestamps at different granularities. As well as colorizing the different log levels.

Simple Use Case

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

fn main() {
    stderrlog::new().module(module_path!()).init().unwrap();

    error!("some failure");

    // ...
}

StructOpt Example

#[macro_use]
extern crate log;
extern crate stderrlog;
#[macro_use]
extern crate structopt;

use structopt::StructOpt;

/// A StructOpt example
#[derive(StructOpt, Debug)]
#[structopt()]
struct Opt {
    /// Silence all output
    #[structopt(short = "q", long = "quiet")]
    quiet: bool,
    /// Verbose mode (-v, -vv, -vvv, etc)
    #[structopt(short = "v", long = "verbose", parse(from_occurrences))]
    verbose: usize,
    /// Timestamp (sec, ms, ns, none)
    #[structopt(short = "t", long = "timestamp")]
    ts: Option<stderrlog::Timestamp>,
}

fn main() {
    let opt = Opt::from_args();

    stderrlog::new()
        .module(module_path!())
        .quiet(opt.quiet)
        .verbosity(opt.verbose)
        .timestamp(opt.ts.unwrap_or(stderrlog::Timestamp::Off))
        .init()
        .unwrap();
    trace!("trace message");
    debug!("debug message");
    info!("info message");
    warn!("warn message");
    error!("error message");
}

docopt Example

extern crate docopt;
#[macro_use]
extern crate log;
extern crate rustc_serialize;
extern crate stderrlog;

use docopt::Docopt;

const USAGE: &'static str = "
Usage: program [-q] [-v...]
";

#[derive(Debug, RustcDecodable)]
struct Args {
    flag_q: bool,
    flag_v: usize,
}

fn main() {
    let args: Args = Docopt::new(USAGE)
                            .and_then(|d| d.decode())
                            .unwrap_or_else(|e| e.exit());

    stderrlog::new()
            .module(module_path!())
            .quiet(args.flag_q)
            .timestamp(stderrlog::Timestamp::Second)
            .verbosity(args.flag_v)
            .init()
            .unwrap();
    trace!("trace message");
    debug!("debug message");
    info!("info message");
    warn!("warn message");
    error!("error message");

    // ...
}

clap Example

#[macro_use]
extern crate clap;
#[macro_use]
extern crate log;
extern crate stderrlog;

use clap::{Arg, App};
use std::str::FromStr;

fn main() {
    let m = App::new("stderrlog example")
        .version(crate_version!())
        .arg(Arg::with_name("verbosity")
             .short("v")
             .multiple(true)
             .help("Increase message verbosity"))
        .arg(Arg::with_name("quiet")
             .short("q")
             .help("Silence all output"))
        .arg(Arg::with_name("timestamp")
             .short("t")
             .help("prepend log lines with a timestamp")
             .takes_value(true)
             .possible_values(&["none", "sec", "ms", "ns"]))
        .get_matches();

    let verbose = m.occurrences_of("verbosity") as usize;
    let quiet = m.is_present("quiet");
    let ts = m.value_of("timestamp").map(|v| {
        stderrlog::Timestamp::from_str(v).unwrap_or_else(|_| {
            clap::Error {
                message: "invalid value for 'timestamp'".into(),
                kind: clap::ErrorKind::InvalidValue,
                info: None,
            }.exit()
        })
    }).unwrap_or(stderrlog::Timestamp::Off);

    stderrlog::new()
        .module(module_path!())
        .quiet(quiet)
        .verbosity(verbose)
        .timestamp(ts)
        .init()
        .unwrap();
    trace!("trace message");
    debug!("debug message");
    info!("info message");
    warn!("warn message");
    error!("error message");
}

log Compatibility

The 0.3.x versions of stderrlog aim to provide compatibility with applications using log 0.3.x

Rust Compatibility

stderrlog is serious about backwards compat. stderrlog pins the minimum required version of Rust in the CI build. Bumping the minimum version of Rust is a minor breaking change and requires a minor version to be bumped.

The minimum supported Rust version for this release is 1.16.0.

Module Level Logging

stderrlog has the ability to limit the components which can log. Many crates use log but you may not want their output in your application. For example hyper makes heavy use of log but when your application receives -vvvvv to enable the trace!() messages you don't want the output of hyper's trace!() level.

To support this stderrlog includes a module() method allowing you to specify the modules that are allowed to log. The examples above use the module_path!() macro to enable logging only for the binary itself but none of its dependencies. To enable logging from extra crates just add another call to module() with the name of the crate. To enable logging for only a module within that crate specifiy crate::module to module(). crates and modules will be named the same way would would include them in source code with use (e.g. some-crate would be some_crate).

For a good example of how the module level logging works see the large-example crate under examples, you'll want to run the following binaries to see all the examples:

  • cargo run --bin large-example --
  • cargo run --bin another --
  • cargo run --bin yet --

Structs

StdErrLog

Data specific to this logger

Enums

ColorChoice

ColorChoice represents the color preferences of an end user.

Timestamp

State of the timestampping in the logger.

Functions

new

creates a new stderr logger