فهرست منبع

Adding optional color support

Adds a default feature that colorizes output based on log level. One can
opt out of colorized output and its dependencies with `default-feature =
false` in Cargo.toml.

Signed-off-by: John Moon <johncarlmoon@gmail.com>
John Moon 6 سال پیش
والد
کامیت
57bd85d7b5
2فایلهای تغییر یافته به همراه22 افزوده شده و 1 حذف شده
  1. 4 0
      Cargo.toml
  2. 18 1
      src/lib.rs

+ 4 - 0
Cargo.toml

@@ -6,6 +6,10 @@ authors = ["Sam Clements <sam@borntyping.co.uk>"]
 description = "A logger that prints all messages with a readable output format"
 repository = "https://github.com/borntyping/rust-simple_logger"
 
+[features]
+default = ["colored"]
+
 [dependencies]
 log = { version = "^0.4.1", features = ["std"] }
 time = "^0.1.25"
+colored = { version = "^1.6", optional = true }

+ 18 - 1
src/lib.rs

@@ -3,6 +3,9 @@
 extern crate log;
 extern crate time;
 
+#[cfg(feature = "colored")] extern crate colored;
+#[cfg(feature = "colored")] use colored::*;
+
 use log::{Log,Level,Metadata,Record,SetLoggerError};
 
 struct SimpleLogger {
@@ -16,10 +19,24 @@ impl Log for SimpleLogger {
 
     fn log(&self, record: &Record) {
         if self.enabled(record.metadata()) {
+            let level_string = {
+                #[cfg(feature = "colored")] {
+                    match record.level() {
+                        Level::Error => record.level().to_string().red(),
+                        Level::Warn => record.level().to_string().yellow(),
+                        Level::Info => record.level().to_string().cyan(),
+                        Level::Debug => record.level().to_string().purple(),
+                        Level::Trace => record.level().to_string().normal(),
+                    }
+                }
+                #[cfg(not(feature = "colored"))] {
+                    record.level().to_string()
+                }
+            };
             println!(
                 "{} {:<5} [{}] {}",
                 time::strftime("%Y-%m-%d %H:%M:%S", &time::now()).unwrap(),
-                record.level().to_string(),
+                level_string,
                 record.module_path().unwrap_or_default(),
                 record.args());
         }