Disable coloring when output isn't a tty.

This commit is contained in:
Sergio Benitez 2017-06-19 18:29:26 -07:00
parent 539a7fc55b
commit ce363810c5
3 changed files with 17 additions and 11 deletions

View File

@ -18,7 +18,7 @@ categories = ["web-programming::http-server"]
tls = ["rustls", "hyper-rustls"]
[dependencies]
yansi = "0.3"
yansi = { version = "0.3", features = ["nightly"] }
log = "0.3"
url = "1"
toml = "0.4"
@ -34,6 +34,7 @@ rustls = { version = "0.9.0", optional = true }
cookie = { version = "0.9.1", features = ["percent-encode", "secure"] }
hyper = { version = "0.10.11", default-features = false }
ordermap = "0.2"
isatty = "0.1"
[dependencies.hyper-rustls]
git = "https://github.com/SergioBenitez/hyper-rustls"

View File

@ -116,6 +116,7 @@ extern crate memchr;
extern crate base64;
extern crate smallvec;
extern crate ordermap;
extern crate isatty;
#[cfg(test)] #[macro_use] extern crate lazy_static;

View File

@ -4,7 +4,7 @@ use std::str::FromStr;
use std::fmt;
use log::{self, Log, LogLevel, LogRecord, LogMetadata};
use yansi::Color::*;
use yansi::Paint;
struct RocketLogger(LoggingLevel);
@ -112,27 +112,27 @@ impl Log for RocketLogger {
// In Rocket, we abuse target with value "_" to indicate indentation.
if record.target() == "_" && self.0 != LoggingLevel::Critical {
print!(" {} ", White.paint("=>"));
print!(" {} ", Paint::white("=>"));
}
use log::LogLevel::*;
match level {
Info => println!("{}", Blue.paint(record.args())),
Trace => println!("{}", Purple.paint(record.args())),
Info => println!("{}", Paint::blue(record.args())),
Trace => println!("{}", Paint::purple(record.args())),
Error => {
println!("{} {}",
Red.paint("Error:").bold(),
Red.paint(record.args()))
Paint::red("Error:").bold(),
Paint::red(record.args()))
}
Warn => {
println!("{} {}",
Yellow.paint("Warning:").bold(),
Yellow.paint(record.args()))
Paint::yellow("Warning:").bold(),
Paint::yellow(record.args()))
}
Debug => {
let loc = record.location();
print!("\n{} ", Blue.paint("-->").bold());
println!("{}:{}", Blue.paint(loc.file()), Blue.paint(loc.line()));
print!("\n{} ", Paint::blue("-->").bold());
println!("{}:{}", Paint::blue(loc.file()), Paint::blue(loc.line()));
println!("{}", record.args());
}
}
@ -141,6 +141,10 @@ impl Log for RocketLogger {
#[doc(hidden)]
pub fn try_init(level: LoggingLevel, verbose: bool) {
if !::isatty::stdout_isatty() {
Paint::disable();
}
let result = log::set_logger(|max_log_level| {
max_log_level.set(level.max_log_level().to_log_level_filter());
Box::new(RocketLogger(level))