瀏覽代碼

Merge pull request #4 from JohnCMoon/colorizing

Adding optional colorized output
Sam Clements 6 年之前
父節點
當前提交
83ed495536
共有 3 個文件被更改,包括 30 次插入1 次删除
  1. 4 0
      Cargo.toml
  2. 8 0
      README.md
  3. 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.5", features = ["std"] }
 chrono = "0.4.6"
+colored = { version = "^1.6", optional = true }

+ 8 - 0
README.md

@@ -35,6 +35,14 @@ You can run the above example with:
 cargo run --example init
 ```
 
+If you want to remove the colorized output and its dependencies, add the
+the following to your Cargo.toml:
+
+```
+[dependencies.simple_logger]
+default-features = false
+```
+
 Licence
 -------
 

+ 18 - 1
src/lib.rs

@@ -3,6 +3,9 @@
 extern crate log;
 extern crate chrono;
 
+#[cfg(feature = "colored")] extern crate colored;
+#[cfg(feature = "colored")] use colored::*;
+
 use log::{Log,Level,Metadata,Record,SetLoggerError};
 use chrono::Local;
 
@@ -17,10 +20,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} [{}] {}",
                 Local::now().format("%Y-%m-%d %H:%M:%S,%3f"),
-                record.level(),
+                level_string,
                 record.module_path().unwrap_or_default(),
                 record.args());
         }