loggerv-0.7.2/.gitignore010064400017500001750000000000321315670401600133740ustar0000000000000000target *.rs.bk Cargo.lock loggerv-0.7.2/.travis.yml010064400017500001750000000010171320661511000135110ustar0000000000000000sudo: false language: rust rust: - nightly - beta - stable matrix: allow_failures: - rust: nightly before_script: - pip install 'travis-cargo<0.2' --user - export PATH=$HOME/.local/bin:$PATH script: - travis-cargo build - travis-cargo test - travis-cargo bench - travis-cargo --only stable doc addons: apt: packages: - libcurl4-openssl-dev - libelf-dev - libdw-dev after_success: - travis-cargo coveralls --no-sudo notifications: email: on_success: change on_failure: always loggerv-0.7.2/Cargo.toml.orig010064400017500001750000000016461352560212300143030ustar0000000000000000[package] authors = ["Eirik Albrigtsen ", "Christopher Field "] description = "A simple log implementation that logs to stdout and stderr with colors" documentation = "http://clux.github.io/loggerv" keywords = ["log", "logger", "stdio", "cli"] categories = ["command-line-utilities"] license = "MIT" name = "loggerv" repository = "https://github.com/clux/loggerv" version = "0.7.2" readme = "README.md" [dependencies] atty = "0.2" ansi_term = "0.12.0" log = { version = "0.4", features = ["std"] } [dev-dependencies] clap = "2.1.2" [[example]] name = "quick" path = "examples/quick.rs" [[example]] name = "run-time-config" path = "examples/run_time_config.rs" [[example]] name = "compile-time-config" path = "examples/compile_time_config.rs" [[example]] name = "cfg-config" path = "examples/cfg_config.rs" [[example]] name = "output-config" path = "examples/output_config.rs" loggerv-0.7.2/Cargo.toml0000644000000027260000000000000105530ustar00# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] name = "loggerv" version = "0.7.2" authors = ["Eirik Albrigtsen ", "Christopher Field "] description = "A simple log implementation that logs to stdout and stderr with colors" documentation = "http://clux.github.io/loggerv" readme = "README.md" keywords = ["log", "logger", "stdio", "cli"] categories = ["command-line-utilities"] license = "MIT" repository = "https://github.com/clux/loggerv" [[example]] name = "quick" path = "examples/quick.rs" [[example]] name = "run-time-config" path = "examples/run_time_config.rs" [[example]] name = "compile-time-config" path = "examples/compile_time_config.rs" [[example]] name = "cfg-config" path = "examples/cfg_config.rs" [[example]] name = "output-config" path = "examples/output_config.rs" [dependencies.ansi_term] version = "0.12.0" [dependencies.atty] version = "0.2" [dependencies.log] version = "0.4" features = ["std"] [dev-dependencies.clap] version = "2.1.2" loggerv-0.7.2/LICENSE010064400017500001750000000020671315670401600124230ustar0000000000000000(The MIT License) Copyright (c) 2016 Eirik Albrigtsen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. loggerv-0.7.2/README.md010064400017500001750000000053641324657541400127100ustar0000000000000000# loggerv [![build status](https://secure.travis-ci.org/clux/loggerv.svg)](http://travis-ci.org/clux/loggerv) [![coverage status](http://img.shields.io/coveralls/clux/loggerv.svg)](https://coveralls.io/r/clux/loggerv) [![crates status](https://img.shields.io/crates/v/loggerv.svg)](https://crates.io/crates/loggerv) A simple `stdout` and `stderr` writing `Logger` implementation of the `log` crate, using `ansi_term` for colors and configured via a log level. Designed for simple Command Line Interfaces (CLIs). ## Usage First, add this to your `Cargo.toml`: ```toml [dependencies] log = "0.4" loggerv = "0.7" ``` Next, add this to the `main.rs` or the file containing the `main` function for your CLI program: ```rust extern crate loggerv; ``` ## Getting Started Clone this repository, then run the following commands to see the log level change: ```bash $ cargo run --example quick $ cargo run --example quick -- -v $ cargo run --example quick -- -vv $ cargo run --example quick -- -vvv ``` This will run an example that uses the [clap](https://crates.io/crates/clap) argument parser to change the log level at run-time based on the number of `-v` arguments that are passed to the application. As the occurrence of the `-v` argument increases, the number of log statements that are displayed should increase. Next, run the following commands: ```bash $ cargo run --example compile-time-config ``` This will run an example that changes the output from defaults at compile-time. The following commands will demonstration configuration at run-time: ```bash $ cargo run --example run-time-config $ cargo run --example run-time-config -- -v $ cargo run --example run-time-config -- -vv $ cargo run --example run-time-config -- -vvv $ cargo run --example run-time-config -- -vvv $ cargo run --example run-time-config -- -vvv -l $ cargo run --example run-time-config -- -vvv -l -d $ cargo run --example run-time-config -- -vvv -l -d --no-module-path $ cargo run --example run-time-config -- -vvv -l -d --no-module-path --no-color ``` Similar to the quick example, as the occurrence of the `-v` argument increases, the number of log statements that are displayed should increase. As the various configuration arguments, i.e. `-l`, `-d`, etc. are added, the format of the log statements change. The `-h,--help` flag can be used to display information about the various flags and their effects on logging and output. Finally, run the following commands to demonstration build profile configuration: ```bash $ cargo run --example cfg-config $ cargo run --release --example cfg-config ``` The number of log statements are displayed based on the build profile, either Debug or Release. ## [Documentation](http://clux.github.io/loggerv) ## License MIT-Licensed. See LICENSE file for details. loggerv-0.7.2/examples/cfg_config.rs010064400017500001750000000043411323017063100156540ustar0000000000000000//! An example using the Builder pattern API to configure the logger based on conditional //! compilation. //! //! The default output is `module::path: message`, and the "tag", which is the text to the left of //! the colon, is colorized. This example shows how to change the output based on a conditional //! compilation, such as a Debug versus Release build. In a Debug build, the default output is //! used with a maximum level of TRACE. In a Release build, the module path is replaced with the //! level and the maximum level is limited to INFO. //! //! The [clap](https://crates.io/crates/clap) argument parser is used in this example, but loggerv //! works with any argument parser. extern crate ansi_term; #[macro_use] extern crate log; extern crate loggerv; fn main() { // Add the following line near the beginning of the main function for an application to enable // colorized output on Windows 10. // // Based on documentation for the ansi_term crate, Windows 10 supports ANSI escape characters, // but it must be enabled first using the `ansi_term::enable_ansi_support()` function. It is // conditionally compiled and only exists for Windows builds. To avoid build errors on // non-windows platforms, a cfg guard should be put in place. #[cfg(windows)] ansi_term::enable_ansi_support().unwrap(); // This is the correct way to determine the build profile using the `cfg` macro according to // this [discussion](https://users.rust-lang.org/t/conditional-compilation-for-debug-release/1098) // and the [documentation](http://doc.crates.io/manifest.html#the-profile-sections) for the // Cargo manifest. if cfg!(debug_assertions) { loggerv::Logger::new() .max_level(log::Level::Trace) } else { loggerv::Logger::new() .no_module_path() .level(true) .max_level(log::Level::Info) }.init().unwrap(); error!("This is printed to stderr with a Debug or Release build"); warn!("This is printed to stderr with a Debug or Release build"); info!("This is printed to stdout with a Debug or Release build"); debug!("This is only printed to stdout with a Debug build"); trace!("This is not printed to stdout with a Debug build"); } loggerv-0.7.2/examples/compile_time_config.rs010064400017500001750000000032721352560151000175670ustar0000000000000000//! An example using the Builder pattern API to configure the logger at compile-time. //! //! The default output is `module::path: message`, and the "tag", which is the text to the left of //! the colon, is colorized. This example shows how to change the output to: `level: message` with //! no colorization. It also demonstrates explicitly setting the log level with the `max_level` //! instead of implicitly with a verbosity. //! //! The [clap](https://crates.io/crates/clap) argument parser is used in this example, but loggerv //! works with any argument parser. extern crate ansi_term; #[macro_use] extern crate log; extern crate loggerv; fn main() { // Add the following line near the beginning of the main function for an application to enable // colorized output on Windows 10. // // Based on documentation for the ansi_term crate, Windows 10 supports ANSI escape characters, // but it must be enabled first using the `ansi_term::enable_ansi_support()` function. It is // conditionally compiled and only exists for Windows builds. To avoid build errors on // non-windows platforms, a cfg guard should be put in place. #[cfg(windows)] ansi_term::enable_ansi_support().unwrap(); loggerv::Logger::new() .max_level(log::Level::Info) .level(true) .no_module_path() .no_colors() .init() .unwrap(); error!("This is printed to stderr with this configuration"); warn!("This is printed to stderr with this configuration"); info!("This is printed to stdout with this configuration"); debug!("This is not printed to stdout with this configuration"); trace!("This is not printed to stdout with this configuration"); } loggerv-0.7.2/examples/output_config.rs010064400017500001750000000044661323017063100164650ustar0000000000000000//! An example using the Builder pattern API to configure the logger at run-time to change //! the output stream for the INFO, DEBUG, and TRACE levels from `stdout` to `stderr`. //! //! The default output stream for INFO, DEBUG, and TRACE levels is `stdout`. This example //! demonstrates changing from the defaults at run-time, but it can also be done at compile-time. //! //! The [clap](https://crates.io/crates/clap) argument parser is used in this example, but loggerv //! works with any argument parser. extern crate ansi_term; #[macro_use] extern crate log; extern crate loggerv; extern crate clap; use clap::{Arg, App}; use loggerv::Output; fn main() { // Add the following line near the beginning of the main function for an application to enable // colorized output on Windows 10. // // Based on documentation for the ansi_term crate, Windows 10 supports ANSI escape characters, // but it must be enabled first using the `ansi_term::enable_ansi_support()` function. It is // conditionally compiled and only exists for Windows builds. To avoid build errors on // non-windows platforms, a cfg guard should be put in place. #[cfg(windows)] ansi_term::enable_ansi_support().unwrap(); let args = App::new("app") .arg(Arg::with_name("v") .short("v") .multiple(true) .help("Sets the level of verbosity")) .arg(Arg::with_name("debug") .short("d") .long("debug") .help("Changes the output stream for INFO, DEBUG, and TRACE from stdout to stderr.")) .get_matches(); if args.is_present("debug") { loggerv::Logger::new() .output(&log::Level::Info, Output::Stderr) .output(&log::Level::Debug, Output::Stderr) .output(&log::Level::Trace, Output::Stderr) } else { loggerv::Logger::new() }.verbosity(args.occurrences_of("v")) .init() .unwrap(); error!("This is always printed to stderr"); warn!("This too is always printed to stderr"); info!("This is optionally printed to stdout or stderr based on the verbosity and the debug flag"); debug!("This is optionally printed to stdout or stderr based on the verbosity and the debug flag"); trace!("This is optionally printed to stdout or stderr based on the verbosity and the debug flag"); } loggerv-0.7.2/examples/quick.rs010064400017500001750000000033721320661423000147100ustar0000000000000000//! An example using the Builder pattern API to configure the logger at run-time based on command //! line arguments. //! //! The default output is `module::path: message`, and the "tag", which is the text to the left of //! the colon, is colorized. This example allows the user to dynamically change the output based //! on command line arguments. //! //! The [clap](https://crates.io/crates/clap) argument parser is used in this example, but loggerv //! works with any argument parser. extern crate ansi_term; #[macro_use] extern crate log; extern crate loggerv; extern crate clap; use clap::{Arg, App}; fn main() { // Add the following line near the beginning of the main function for an application to enable // colorized output on Windows 10. // // Based on documentation for the ansi_term crate, Windows 10 supports ANSI escape characters, // but it must be enabled first using the `ansi_term::enable_ansi_support()` function. It is // conditionally compiled and only exists for Windows builds. To avoid build errors on // non-windows platforms, a cfg guard should be put in place. #[cfg(windows)] ansi_term::enable_ansi_support().unwrap(); let args = App::new("app") .arg(Arg::with_name("v") .short("v") .multiple(true) .help("Sets the level of verbosity")) .get_matches(); loggerv::init_with_verbosity(args.occurrences_of("v")).unwrap(); error!("This is always printed to stderr"); warn!("This too is always printed to stderr"); info!("This is optional info printed to stdout"); // for ./app -v or higher debug!("This is optional debug printed to stdout"); // for ./app -vv or higher trace!("This is optional trace printed to stdout"); // for ./app -vvv } loggerv-0.7.2/examples/run_time_config.rs010064400017500001750000000051021352560151000167350ustar0000000000000000//! An example using the Builder pattern API to configure the logger at run-time based on command //! line arguments. //! //! The default output is `module::path: message`, and the "tag", which is the text to the left of //! the colon, is colorized. This example allows the user to dynamically change the output based //! on command line arguments. //! //! The [clap](https://crates.io/crates/clap) argument parser is used in this example, but loggerv //! works with any argument parser. extern crate ansi_term; #[macro_use] extern crate log; extern crate loggerv; extern crate clap; use clap::{Arg, App}; fn main() { // Add the following line near the beginning of the main function for an application to enable // colorized output on Windows 10. // // Based on documentation for the ansi_term crate, Windows 10 supports ANSI escape characters, // but it must be enabled first using the `ansi_term::enable_ansi_support()` function. It is // conditionally compiled and only exists for Windows builds. To avoid build errors on // non-windows platforms, a cfg guard should be put in place. #[cfg(windows)] ansi_term::enable_ansi_support().unwrap(); let args = App::new("app") .arg(Arg::with_name("v") .short("v") .multiple(true) .help("Sets the level of verbosity")) .arg(Arg::with_name("debug") .short("d") .long("debug") .help("Adds the line numbers to log statements")) .arg(Arg::with_name("no-module-path") .long("no-module-path") .help("Disables the module path in the log statements")) .arg(Arg::with_name("no-color") .long("no-color") .help("Disables colorized output")) .arg(Arg::with_name("level") .short("l") .long("level") .help("Adds the log level to the log statements. This will also surround the module path in square brackets.")) .get_matches(); loggerv::Logger::new() .verbosity(args.occurrences_of("v")) .level(args.is_present("level")) .line_numbers(args.is_present("debug")) .module_path(!args.is_present("no-module-path")) .colors(!args.is_present("no-color")) .init() .unwrap(); error!("This is always printed to stderr"); warn!("This too is always printed to stderr"); info!("This is optionally printed to stdout based on the verbosity"); debug!("This is optionally printed to stdout based on the verbosity"); trace!("This is optionally printed to stdout based on the verbosity"); } loggerv-0.7.2/src/lib.rs010064400017500001750000000775111352560151000133220ustar0000000000000000//! A simple `io::stdout` and `io::stderr` writing `Logger` implementation from the //! `log` crate, using the `ansi_term` crate for colors and configured at runtime via a verbosity //! or at compile time with simple function calls. Designed for simple Command Line Interfaces //! (CLIs). //! //! This library includes a Builder pattern API for configuring a logger and three initializing //! helper functions to create a default logger. Ensure you create and initialize only once //! a global logger with the Builder pattern API or use one of the three public helper functions //! early in your program as shown in the examples below. //! //! The default configuration colorizes the "tag" portion of the log statement, where the tag is //! the text to the left of a separator, defaulted as the colon (`:`). The message is the //! portion to the right of the separator and it is _not_ ever colorized. The tag includes only the //! module path and the separator by default. //! //! ## Example //! //! The standard example with [clap](https://crates.io/crates/clap) as the arg parser using the //! default configuration. //! //! ``` //! #[macro_use] extern crate log; //! extern crate clap; //! extern crate loggerv; //! //! use clap::{Arg, App}; //! //! fn main() { //! let args = App::new("app") //! .arg(Arg::with_name("v") //! .short("v") //! .multiple(true) //! .help("Sets the level of verbosity")) //! .get_matches(); //! //! loggerv::init_with_verbosity(args.occurrences_of("v")).unwrap(); //! //! error!("This is always printed"); //! warn!("This too is always printed to stderr"); //! info!("This is optionally printed to stdout"); // for ./app -v or higher //! debug!("This is optionally printed to stdout"); // for ./app -vv or higher //! trace!("This is optionally printed to stdout"); // for ./app -vvv //! } //! ``` //! //! But obviously use whatever argument parsing methods you prefer. //! //! ## Example //! //! For a compile time switch, all you really need is `log` (for the macros) and `loggerv` for how //! to print what's being sent to the macros with the default configuration. //! //! ``` //! #[macro_use] extern crate log; //! extern crate loggerv; //! //! use log::Level; //! //! fn main() { //! loggerv::init_with_level(Level::Info).unwrap(); //! debug!("This is a debug {}", "message"); // Not printed to stdout //! error!("This is printed by default"); // Printed to stderr //! } //! ``` //! //! ## Example //! //! If you don't really care at all you could just use the plain `init_quiet` function to only show //! warnings and errors with the default configuration: //! //! ``` //! #[macro_use] extern crate log; //! extern crate loggerv; //! //! fn main() { //! loggerv::init_quiet().unwrap(); //! info!("Hidden"); //! error!("This is printed by default"); //! } //! ``` //! //! ## Example //! //! If you want to configure the output, the Builder pattern API can be used. //! //! ``` //! #[macro_use] extern crate log; //! extern crate clap; //! extern crate loggerv; //! //! use clap::{Arg, App}; //! //! fn main() { //! let args = App::new("app") //! .arg(Arg::with_name("v") //! .short("v") //! .multiple(true) //! .help("Sets the level of verbosity")) //! .get_matches(); //! //! loggerv::Logger::new() //! .verbosity(args.occurrences_of("v")) //! .level(true) //! .line_numbers(true) //! .separator(" = ") //! .module_path(false) //! .colors(false) //! .init() //! .unwrap(); //! //! error!("This is always printed to stderr"); //! warn!("This too is always printed to stderr"); //! info!("This is optionally printed to stdout"); // for ./app -v or higher //! debug!("This is optionally printed to stdout"); // for ./app -vv or higher //! trace!("This is optionally printed to stdout"); // for ./app -vvv //! } //! ``` //! //! See the [documentation](https://docs.rs/log/0.4.1/log/) for the //! [log](https://crates.io/crates/log) crate for more information about its API. //! extern crate log; extern crate atty; extern crate ansi_term; use log::{SetLoggerError}; use std::io::{self, Write}; use ansi_term::Colour; pub const DEFAULT_COLORS: bool = true; pub const DEFAULT_DEBUG_COLOR: Colour = Colour::Fixed(7); // light grey pub const DEFAULT_ERROR_COLOR: Colour = Colour::Fixed(9); // bright red pub const DEFAULT_INCLUDE_LEVEL: bool = false; pub const DEFAULT_INCLUDE_LINE_NUMBERS: bool = false; pub const DEFAULT_INCLUDE_MODULE_PATH: bool = true; pub const DEFAULT_INFO_COLOR: Colour = Colour::Fixed(10); // bright green pub const DEFAULT_LEVEL: log::Level = log::Level::Warn; pub const DEFAULT_OFFSET: u64 = 1; pub const DEFAULT_SEPARATOR: &str = ": "; pub const DEFAULT_TRACE_COLOR: Colour = Colour::Fixed(8); // grey pub const DEFAULT_WARN_COLOR: Colour = Colour::Fixed(11); // bright yellow pub const MODULE_PATH_UNKNOWN: &str = "unknown"; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Output { Stderr, Stdout, } #[derive(Debug, Clone, Copy, PartialEq)] struct Level { output: Output, color: Colour, } #[derive(Debug, Clone, PartialEq)] pub struct Logger { colors: bool, include_level: bool, include_line_numbers: bool, include_module_path: bool, level: log::Level, offset: u64, separator: String, verbosity: Option, error: Level, warn: Level, info: Level, debug: Level, trace: Level, module_path_filters: Vec, } impl Logger { /// Creates a new instance of the verbosity-based logger. /// /// The default level is WARN. Color is enabled if the parent application or library is running /// from a terminal, i.e. running a tty. The default separator is the ": " string. The default /// output format is `module path: message`. The following default colors are used: /// /// | Level | Color | /// |-------|---------------| /// | Error | Bright Red | /// | Warn | Bright Yellow | /// | Info | Bright Green | /// | Debug | Light Grey | /// | Trace | Grey | pub fn new() -> Logger { Logger { colors: DEFAULT_COLORS && atty::is(atty::Stream::Stdout) && atty::is(atty::Stream::Stderr), include_level: DEFAULT_INCLUDE_LEVEL, include_line_numbers: DEFAULT_INCLUDE_LINE_NUMBERS, include_module_path: DEFAULT_INCLUDE_MODULE_PATH, level: DEFAULT_LEVEL, offset: DEFAULT_OFFSET, separator: String::from(DEFAULT_SEPARATOR), verbosity: None, error: Level { output: Output::Stderr, color: DEFAULT_ERROR_COLOR, }, warn: Level { output: Output::Stderr, color: DEFAULT_WARN_COLOR, }, info: Level { output: Output::Stderr, color: DEFAULT_INFO_COLOR, }, debug: Level { output: Output::Stderr, color: DEFAULT_DEBUG_COLOR, }, trace: Level { output: Output::Stderr, color: DEFAULT_TRACE_COLOR, }, module_path_filters: Vec::new(), } } /// Sets the color for a level. /// /// # Example /// /// ``` /// #[macro_use] extern crate log; /// extern crate loggerv; /// extern crate ansi_term; /// /// use log::Level; /// use ansi_term::Colour; /// /// fn main() { /// loggerv::Logger::new() /// .color(&Level::Error, Colour::Fixed(7)) /// .init() /// .unwrap(); /// /// error!("This is printed in light grey instead of bright red"); /// } /// ``` pub fn color(mut self, l: &log::Level, c: Colour) -> Self { match *l { log::Level::Error => self.error.color = c, log::Level::Warn => self.warn.color = c, log::Level::Info => self.info.color = c, log::Level::Debug => self.debug.color = c, log::Level::Trace => self.trace.color = c, } self } /// Sets the separator string. /// /// The separator is the string between the "tag" and the message that make up a log statement. /// The tag will be colorized if enabled, while the message will not. The default is `: `. /// /// If the level, line numbers, and module path are all _not_ included in the log statement, /// then the separator is changed to the empty string to avoid printing a lone string or /// character before each message portion of the log statement. /// /// # Example /// /// ```rust /// #[macro_use] extern crate log; /// extern crate loggerv; /// /// fn main() { /// loggerv::Logger::new() /// .separator(" = ") /// .init() /// .unwrap(); /// /// error!("This is printed with an equal sign between the module path and this message"); /// } /// ``` pub fn separator(mut self, s: &str) -> Self { self.separator = String::from(s); self } /// Enables or disables colorizing the output. /// /// If the logger is _not_ used in a terminal, then the output is _not_ colorized regardless of /// this value. /// /// # Example /// /// ```rust /// #[macro_use] extern crate log; /// extern crate loggerv; /// /// fn main() { /// loggerv::Logger::new() /// .colors(false) /// .init() /// .unwrap(); /// /// error!("This is printed without any colorization"); /// } /// ``` pub fn colors(mut self, c: bool) -> Self { self.colors = c && atty::is(atty::Stream::Stdout) && atty::is(atty::Stream::Stderr); self } /// Disables colorizing the output. /// /// The default is to colorize the output unless `stdout` and `stderr` are redirected or piped, /// i.e. not a tty. /// /// # Example /// /// ```rust /// #[macro_use] extern crate log; /// extern crate loggerv; /// /// fn main() { /// loggerv::Logger::new() /// .no_colors() /// .init() /// .unwrap(); /// /// error!("This is printed without any colorization"); /// } /// ``` pub fn no_colors(mut self) -> Self { self. colors = false; self } /// Enables or disables including line numbers in the "tag" portion of the log statement. /// /// The tag is the text to the left of the separator. /// /// # Example /// /// ```rust /// #[macro_use] extern crate log; /// extern crate loggerv; /// /// fn main() { /// loggerv::Logger::new() /// .line_numbers(true) /// .init() /// .unwrap(); /// /// error!("This is printed with the module path and the line number surrounded by /// parentheses"); /// } /// ``` pub fn line_numbers(mut self, i: bool) -> Self { self.include_line_numbers = i; self } /// Enables or disables including the level in the log statement's tag portion. The tag of the /// log statement is the text to the left of the separator. /// /// If the level and the module path are both inculded, then the module path is surrounded by /// square brackets. /// /// # Example /// /// ```rust /// #[macro_use] extern crate log; /// extern crate loggerv; /// /// fn main() { /// loggerv::Logger::new() /// .level(true) /// .init() /// .unwrap(); /// /// error!("This is printed with the 'ERROR' and the module path is surrounded in square /// brackets"); /// } /// ``` pub fn level(mut self, i: bool) -> Self { self.include_level = i; self } /// Explicitly sets the log level instead of through a verbosity. /// /// # Example /// /// ```rust /// #[macro_use] extern crate log; /// extern crate loggerv; /// /// fn main() { /// loggerv::Logger::new() /// .max_level(log::Level::Info) /// .init() /// .unwrap(); /// /// error!("This is printed to stderr"); /// warn!("This is printed to stderr"); /// info!("This is printed to stdout"); /// debug!("This is not printed to stdout"); /// trace!("This is not printed to stdout"); /// } /// ``` pub fn max_level(mut self, l: log::Level) -> Self { self.level = l; // It is important to set the Verbosity to None here because later with the `init` method, // a `None` value indicates the verbosity has _not_ been set or overriden by using this // method (`max_level`). If the verbosity is some value, then it will be used and the use // of this method will be dismissed. self.verbosity = None; self } /// Enables or disables including the module path in the "tag" portion of the log statement. /// /// The tag is the text to the left of the separator. The default is to include the module /// path. Ifthe level is also included, the module path is surrounded by square brackets. /// /// # Example /// /// ```rust /// #[macro_use] extern crate log; /// extern crate loggerv; /// /// fn main() { /// loggerv::Logger::new() /// .module_path(false) /// .init() /// .unwrap(); /// /// error!("This is printed without leading module path and separator"); /// } /// ``` pub fn module_path(mut self, i: bool) -> Self { self.include_module_path = i; self } /// Disables the module path in the "tag" portion of the log statement. /// /// The tag is the text to the left of the separator. The default is to include the module /// path. /// /// # Example /// /// ```rust /// #[macro_use] extern crate log; /// extern crate loggerv; /// /// fn main() { /// loggerv::Logger::new() /// .no_module_path() /// .init() /// .unwrap(); /// /// error!("This is printed without leading module path and separator"); /// } /// ``` pub fn no_module_path(mut self) -> Self { self.include_module_path = false; self } /// Sets the module path filter list. /// /// When any filter is matched as prefix of the log statement module path, the log /// statement will be logged if log level allows. /// Log statements not maching any filter will not be logged. /// /// When not set (default) or set to empty Vec log statements will not be filtered /// by the module path. /// /// # Example /// Log only messages comming from this program. /// /// ```rust /// #[macro_use] extern crate log; /// extern crate loggerv; /// /// fn main() { /// loggerv::Logger::new() /// .module_path_filters(vec![module_path!().to_owned()]) /// .init() /// .unwrap(); /// /// error!("This is printed"); /// } /// ``` pub fn module_path_filters(mut self, filters: Vec) -> Self { self.module_path_filters = filters; self } /// Adds module path filter to the list of module path filters. /// /// When any filter is matched as prefix of the log statement module path, the log /// statement will be logged if log level allows. /// Log statements not maching any filter will not be logged. /// /// When not filters were added log statements will not be filtered /// by the module path. /// /// # Example /// Log only messages comming from this program. /// /// ```rust /// #[macro_use] extern crate log; /// extern crate loggerv; /// /// fn main() { /// loggerv::Logger::new() /// .add_module_path_filter(module_path!()) /// .init() /// .unwrap(); /// /// error!("This is printed"); /// } /// ``` pub fn add_module_path_filter(mut self, filter: impl Into) -> Self { self.module_path_filters.push(filter.into()); self } /// Sets the base level. /// /// The base level is the level used with zero (0) verbosity. The default is WARN. So, ERROR /// and WARN statements will be written and INFO statements will be written with a verbosity of /// 1 or greater. If the base level was changed to ERROR, then only ERROR statements will be /// written and WARN statements will be written with a verbosity of 1 or greater. Use this /// adjust the correlation of verbosity, i.e. number of `-v` occurrences, to level. /// /// # Example /// /// ```rust /// #[macro_use] extern crate log; /// extern crate loggerv; /// /// fn main() { /// loggerv::Logger::new() /// .base_level(log::Level::Error) /// .verbosity(0) /// .init() /// .unwrap(); /// /// error!("This is printed"); /// warn!("This is not printed"); /// info!("This is not printed"); /// } /// ``` /// /// # Example /// /// ```rust /// #[macro_use] extern crate log; /// extern crate loggerv; /// /// fn main() { /// loggerv::Logger::new() /// .base_level(log::Level::Info) /// .verbosity(0) /// .init() /// .unwrap(); /// /// error!("This is printed"); /// warn!("This is also printed"); /// info!("This is now printed, too"); /// } /// ``` pub fn base_level(mut self, b: log::Level) -> Self { self.offset = match b { log::Level::Error => 0, log::Level::Warn => 1, log::Level::Info => 2, log::Level::Debug => 3, log::Level::Trace => 4, }; self } /// Sets the output for a level. /// /// The output is either `stderr` or `stdout`. The default is for ERROR and WARN to be written /// to `stderr` and INFO, DEBUG, and TRACE to `stdout`. /// /// # Example /// /// ```rust /// #[macro_use] extern crate log; /// extern crate loggerv; /// /// use log::Level; /// use loggerv::Output; /// /// fn main() { /// loggerv::Logger::new() /// .output(&Level::Error, Output::Stdout) /// .output(&Level::Warn, Output::Stdout) /// .output(&Level::Info, Output::Stderr) /// .output(&Level::Debug, Output::Stderr) /// .output(&Level::Trace, Output::Stderr) /// .verbosity(0) /// .init() /// .unwrap(); /// /// error!("This is printed on stdout instead of stderr"); /// warn!("This is printed on stdout instead of stderr"); /// info!("This is printed on stderr instead of stdout"); /// debug!("This is printed on stderr instead of stdout"); /// trace!("This is printed on stderr instead of stdout"); /// } /// ``` pub fn output(mut self, l: &log::Level, o: Output) -> Self { match *l { log::Level::Error => self.error.output = o, log::Level::Warn => self.warn.output = o, log::Level::Info => self.info.output = o, log::Level::Debug => self.debug.output = o, log::Level::Trace => self.trace.output = o, } self } /// Sets the level based on verbosity and the offset. /// /// A verbosity of zero (0) is the default, which means ERROR and WARN log statements are /// printed to `stderr`. No other log statements are printed on any of the standard streams /// (`stdout` or `stderr`). As the verbosity is increased, the log level is increased and more /// log statements will be printed to `stdout`. /// /// # Example /// /// ```rust /// #[macro_use] extern crate log; /// extern crate loggerv; /// /// fn main() { /// loggerv::Logger::new() /// .verbosity(1) /// .init() /// .unwrap(); /// /// error!("This is printed to stderr"); /// warn!("This is printed to stderr"); /// info!("This is printed to stdout"); /// debug!("This is not printed to stdout"); /// trace!("This is not printed to stdout"); /// } /// ``` pub fn verbosity(mut self, v: u64) -> Self { self.verbosity = Some(v); self } /// Initializes the logger. /// /// This also consumes the logger. It cannot be further modified after initialization. /// /// # Example /// /// ```rust /// #[macro_use] extern crate log; /// extern crate loggerv; /// /// fn main() { /// loggerv::Logger::new() /// .init() /// .unwrap(); /// /// error!("This is printed to stderr"); /// warn!("This is printed to stderr"); /// info!("This is not printed to stdout"); /// debug!("This is not printed to stdout"); /// trace!("This is not printed to stdout"); /// } /// ``` /// /// # Example /// /// If the tag will be empty because the level, line numbers, and module path were all /// disabled, then the separator is changed to the empty string to avoid writing a long /// character in front of each message for each log statement. /// /// /// ```rust /// #[macro_use] extern crate log; /// extern crate loggerv; /// /// fn main() { /// loggerv::Logger::new() /// .module_path(false) /// .level(false) /// .line_numbers(false) /// .init() /// .unwrap(); /// /// error!("This is printed to stderr without the separator"); /// warn!("This is printed to stderr without the separator"); /// info!("This is not printed to stdout"); /// debug!("This is not printed to stdout"); /// trace!("This is not printed to stdout"); /// } /// ``` pub fn init(mut self) -> Result<(), SetLoggerError> { // If there is no level, line number, or module path in the tag, then the tag will always // be empty. The separator should also be empty so only the message component is printed // for the log statement; otherwise, there is a weird floating colon in front of every log // statement. // // It is better to do it here than in the `log` function because it only has to be // determined once at initialization as opposed to every call to the `log` function. So // a potentially slight performance improvement. if !self.include_level && !self.include_line_numbers && !self.include_module_path { self.separator = String::new(); } // The level is set based on verbosity only if the `verbosity` method has been used and // _not_ overwridden a later call to the `max_level` method. If neither the `verbosity` or // `max_level` method is used, then the `DEFAULT_LEVEL` is used because it is set with the // `new` function. It makes more sense to calculate the level based on verbosity _after_ // all configuration methods have been called as opposed to during the call to the // `verbosity` method. This change enables the offset feature so that the `max_level` // method can be used at any time during the "building" procedure before the call to // `init`. Otherwise, calling the `max_level` _after_ the `verbosity` method would have no // effect and be difficult to communicate this limitation to users. if let Some(v) = self.verbosity { self.level = match v + self.offset { 0 => log::Level::Error, 1 => log::Level::Warn, 2 => log::Level::Info, 3 => log::Level::Debug, _ => log::Level::Trace, }; } log::set_max_level(self.level.to_level_filter()); log::set_boxed_logger(Box::new(self)) } /// Gets the color to use for the log statement's tag based on level. fn select_color(&self, l: &log::Level) -> Colour { match *l { log::Level::Error => self.error.color, log::Level::Warn => self.warn.color, log::Level::Info => self.info.color, log::Level::Debug => self.debug.color, log::Level::Trace => self.trace.color, } } /// Gets the output stream to use for the level. fn select_output(&self, l: &log::Level) -> Output { match *l { log::Level::Error => self.error.output, log::Level::Warn => self.warn.output, log::Level::Info => self.info.output, log::Level::Debug => self.debug.output, log::Level::Trace => self.trace.output, } } /// Creates the tag portion of the log statement based on the configuration. /// /// The tag portion is the of the log statement is the text to the left of the separator, while /// the text to the right of the separator is the message. fn create_tag(&self, record: &log::Record) -> String { let level = record.level(); let level_text = if self.include_level { level.to_string() } else { String::new() }; let module_path_text = if self.include_module_path { let pth = record.module_path().unwrap_or(MODULE_PATH_UNKNOWN); if self.include_level { format!(" [{}]", pth) } else { pth.into() } } else { String::new() }; let line_text = if self.include_line_numbers { if let Some(l) = record.line() { format!(" (line {})", l) } else { String::new() } } else { String::new() }; let mut tag = format!("{}{}{}", level_text, module_path_text, line_text); if self.colors { tag = self.select_color(&level).paint(tag).to_string(); } tag } } impl log::Log for Logger { fn enabled(&self, metadata: &log::Metadata) -> bool { metadata.level() <= self.level } fn log(&self, record: &log::Record) { if self.enabled(record.metadata()) { if !self.module_path_filters.is_empty() && !self.module_path_filters.iter().any(|filter| record.module_path().unwrap_or(MODULE_PATH_UNKNOWN).starts_with(filter)) { return } match self.select_output(&record.level()) { Output::Stderr => { writeln!( &mut io::stderr(), "{}{}{}", self.create_tag(&record), self.separator, record.args() ).expect("Writing to stderr"); }, Output::Stdout => { println!( "{}{}{}", self.create_tag(&record), self.separator, record.args() ); }, } } } fn flush(&self) { // println! flushes by itself } } impl Default for Logger { fn default() -> Logger { Logger::new() } } /// Initialize loggerv with a maximal log level. /// /// See the main loggerv documentation page for an example. pub fn init_with_level(level: log::Level) -> Result<(), SetLoggerError> { Logger::new().max_level(level).init() } /// Initialize loggerv with a verbosity level. /// /// Intended to be used with an arg parser counting the amount of -v flags. /// See the main loggerv documentation page for an example. pub fn init_with_verbosity(verbosity: u64) -> Result<(), SetLoggerError> { Logger::new().verbosity(verbosity).init() } /// Initializes loggerv with only warnings and errors. /// /// See the main loggerv documentation page for an example. pub fn init_quiet() -> Result<(), SetLoggerError> { init_with_level(log::Level::Warn) } #[cfg(test)] mod tests { use log; use ansi_term::Colour; use super::*; #[test] fn defaults_are_correct() { let logger = Logger::new(); assert_eq!(logger.include_level, DEFAULT_INCLUDE_LEVEL); assert_eq!(logger.include_line_numbers, DEFAULT_INCLUDE_LINE_NUMBERS); assert_eq!(logger.include_module_path, DEFAULT_INCLUDE_MODULE_PATH); assert_eq!(logger.colors, DEFAULT_COLORS); assert_eq!(logger.level, DEFAULT_LEVEL); assert_eq!(logger.separator, String::from(DEFAULT_SEPARATOR)); assert_eq!(logger.error.color, DEFAULT_ERROR_COLOR); assert_eq!(logger.warn.color, DEFAULT_WARN_COLOR); assert_eq!(logger.info.color, DEFAULT_INFO_COLOR); assert_eq!(logger.debug.color, DEFAULT_DEBUG_COLOR); assert_eq!(logger.trace.color, DEFAULT_TRACE_COLOR); } #[test] fn color_works() { let logger = Logger::new().color(&log::Level::Trace, Colour::Fixed(11)); assert_eq!(logger.trace.color, Colour::Fixed(11)); } #[test] fn separator_works() { const EXPECTED: &str = " = "; let logger = Logger::new().separator(EXPECTED); assert_eq!(logger.separator, EXPECTED); } #[test] fn colors_works() { let logger = Logger::new().colors(false); assert!(!logger.colors); } #[test] fn no_colors_works() { let logger = Logger::new().no_colors(); assert!(!logger.colors); } #[test] fn line_numbers_works() { let logger = Logger::new().line_numbers(true); assert!(logger.include_line_numbers); } #[test] fn level_works() { let logger = Logger::new().level(true); assert!(logger.include_level); } #[test] fn max_level_works() { let logger = Logger::new().max_level(log::Level::Trace); assert_eq!(logger.level, log::Level::Trace); assert!(logger.verbosity.is_none()); } #[test] fn base_level_works() { let logger = Logger::new().base_level(log::Level::Info); assert_eq!(logger.offset, 2); } #[test] fn module_path_works() { let logger = Logger::new().module_path(false); assert!(!logger.include_module_path); } #[test] fn no_module_path_works() { let logger = Logger::new().no_module_path(); assert!(!logger.include_module_path); } #[test] fn verbosity_works() { let logger = Logger::new().verbosity(3); assert_eq!(logger.verbosity, Some(3)); } #[test] fn output_works() { let logger = Logger::new() .output(&log::Level::Error, Output::Stdout) .output(&log::Level::Warn, Output::Stdout) .output(&log::Level::Info, Output::Stderr) .output(&log::Level::Debug, Output::Stderr) .output(&log::Level::Trace, Output::Stderr); assert_eq!(logger.error.output, Output::Stdout); assert_eq!(logger.warn.output, Output::Stdout); assert_eq!(logger.info.output, Output::Stderr); assert_eq!(logger.debug.output, Output::Stderr); assert_eq!(logger.trace.output, Output::Stderr); } #[test] fn init_works() { let result = Logger::new().init(); assert!(result.is_ok()); } #[test] fn select_color_works() { let logger = Logger::new(); assert_eq!(logger.select_color(&log::Level::Error), DEFAULT_ERROR_COLOR); assert_eq!(logger.select_color(&log::Level::Warn), DEFAULT_WARN_COLOR); assert_eq!(logger.select_color(&log::Level::Info), DEFAULT_INFO_COLOR); assert_eq!(logger.select_color(&log::Level::Debug), DEFAULT_DEBUG_COLOR); assert_eq!(logger.select_color(&log::Level::Trace), DEFAULT_TRACE_COLOR); } } loggerv-0.7.2/.cargo_vcs_info.json0000644000000001120000000000000125400ustar00{ "git": { "sha1": "90559539ab294a7f09494ddd4ffffd01b7225bf6" } } loggerv-0.7.2/Cargo.lock0000644000000132250000000000000105240ustar00# This file is automatically @generated by Cargo. # It is not intended for manual editing. [[package]] name = "ansi_term" version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "ansi_term" version = "0.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "atty" version = "0.2.13" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "libc 0.2.62 (registry+https://github.com/rust-lang/crates.io-index)", "winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "bitflags" version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "cfg-if" version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "clap" version = "2.33.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "ansi_term 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", "atty 0.2.13 (registry+https://github.com/rust-lang/crates.io-index)", "bitflags 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "strsim 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)", "textwrap 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)", "unicode-width 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)", "vec_map 0.8.1 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "libc" version = "0.2.62" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "log" version = "0.4.8" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "cfg-if 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "loggerv" version = "0.7.2" dependencies = [ "ansi_term 0.12.0 (registry+https://github.com/rust-lang/crates.io-index)", "atty 0.2.13 (registry+https://github.com/rust-lang/crates.io-index)", "clap 2.33.0 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "strsim" version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "textwrap" version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "unicode-width 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "unicode-width" version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "vec_map" version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "winapi" version = "0.3.7" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", "winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "winapi-i686-pc-windows-gnu" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" [[package]] name = "winapi-x86_64-pc-windows-gnu" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" [metadata] "checksum ansi_term 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ee49baf6cb617b853aa8d93bf420db2383fab46d314482ca2803b40d5fde979b" "checksum ansi_term 0.12.0 (registry+https://github.com/rust-lang/crates.io-index)" = "eaa72766c3585a1f812a3387a7e2c6cab780f899c2f43ff6ea06c8d071fcbb36" "checksum atty 0.2.13 (registry+https://github.com/rust-lang/crates.io-index)" = "1803c647a3ec87095e7ae7acfca019e98de5ec9a7d01343f611cf3152ed71a90" "checksum bitflags 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "3d155346769a6855b86399e9bc3814ab343cd3d62c7e985113d46a0ec3c281fd" "checksum cfg-if 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)" = "b486ce3ccf7ffd79fdeb678eac06a9e6c09fc88d33836340becb8fffe87c5e33" "checksum clap 2.33.0 (registry+https://github.com/rust-lang/crates.io-index)" = "5067f5bb2d80ef5d68b4c87db81601f0b75bca627bc2ef76b141d7b846a3c6d9" "checksum libc 0.2.62 (registry+https://github.com/rust-lang/crates.io-index)" = "34fcd2c08d2f832f376f4173a231990fa5aef4e99fb569867318a227ef4c06ba" "checksum log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)" = "14b6052be84e6b71ab17edffc2eeabf5c2c3ae1fdb464aae35ac50c67a44e1f7" "checksum strsim 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)" = "8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a" "checksum textwrap 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d326610f408c7a4eb6f51c37c330e496b08506c9457c9d34287ecc38809fb060" "checksum unicode-width 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "882386231c45df4700b275c7ff55b6f3698780a650026380e72dabe76fa46526" "checksum vec_map 0.8.1 (registry+https://github.com/rust-lang/crates.io-index)" = "05c78687fb1a80548ae3250346c3db86a80a7cdd77bda190189f2d0a0987c81a" "checksum winapi 0.3.7 (registry+https://github.com/rust-lang/crates.io-index)" = "f10e386af2b13e47c89e7236a7a14a086791a2b88ebad6df9bf42040195cf770" "checksum winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" "checksum winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"