Skip to content

Commit

Permalink
Merge pull request #49 from lucid-kv/improve-logs
Browse files Browse the repository at this point in the history
Improve logging
  • Loading branch information
Clint.Network committed Jan 31, 2020
2 parents bcc5d8a + f7464f5 commit 9ca0fff
Show file tree
Hide file tree
Showing 4 changed files with 150 additions and 20 deletions.
62 changes: 62 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ chashmap = "2.2.2"
tree_magic = "0.2.1"
snafu = "0.6.2"
bytes = "0.5.3"
fern = "0.5.9"
fern = { version = "0.5.9", features = ["colored", "syslog-4"] }
clap = { version = "2.33.0", features = ["yaml"] }
warp = { version = "0.2.0", features = ["tls"] }
log = { version = "0.4.8", features = ["serde"] }
Expand Down
10 changes: 10 additions & 0 deletions src/configuration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ impl Default for Configuration {
},
logging: Logging {
level: LevelFilter::Info,
outputs: vec![LogOutput::Stdout { colored: false }],
},
}
}
Expand Down Expand Up @@ -109,6 +110,15 @@ pub struct Http {
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Logging {
pub level: LevelFilter,
pub outputs: Vec<LogOutput>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "lowercase", tag = "type")]
pub enum LogOutput {
File { path: PathBuf },
Stdout { colored: bool },
Stderr { colored: bool },
}

#[derive(Debug, Clone, Serialize, Deserialize)]
Expand Down
96 changes: 77 additions & 19 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ mod kvstore;
mod lucid;
mod server;

use configuration::{Claims, Configuration};
use configuration::{Claims, Configuration, LogOutput};
use lucid::Lucid;

use std::{
Expand All @@ -22,9 +22,9 @@ use std::{
use app_dirs::{AppDirsError, AppInfo};
use chrono::{DateTime, Duration, Utc};
use clap::App;
use fern::colors::{Color, ColoredLevelConfig};
use fern::Dispatch;
use jsonwebtoken::Header;
use log::LevelFilter;
use rand::Rng;
use ring::digest;
use snafu::{ResultExt, Snafu};
Expand Down Expand Up @@ -57,22 +57,11 @@ const CREDITS: &'static str = "\

#[tokio::main]
async fn main() -> Result<(), Error> {
Dispatch::new()
.format(|out, message, record| {
out.finish(format_args!(
"{} {} [{}] {}",
Utc::now().format("%Y/%m/%d %H:%M:%S"),
record.level(),
record.target(),
message
))
})
.chain(std::io::stdout())
.apply()
.expect("Couldn't start logger");
log::set_max_level(LevelFilter::Debug);

let long_version = format!("{}\n{}\n\nYou can send a tips here: 3BxEYn4RZ3iYETcFpN7nA6VqCY4Hz1tSUK", crate_version!(), CREDITS);
let long_version = format!(
"{}\n{}\n\nYou can send a tips here: 3BxEYn4RZ3iYETcFpN7nA6VqCY4Hz1tSUK",
crate_version!(),
CREDITS
);

let cli_yaml = load_yaml!("cli.yml");
let app = App::from_yaml(&cli_yaml)
Expand Down Expand Up @@ -112,6 +101,49 @@ async fn main() -> Result<(), Error> {
Configuration::get_path().context(GetConfigDir)?
}
};
let config = if config_path.exists() {
serde_yaml::from_reader(File::open(&config_path).context(OpenConfigFile)?)
.context(ReadConfigFile)?
} else {
Configuration::default()
};
log::set_max_level(config.logging.level);

let logging_colors = ColoredLevelConfig::new()
.debug(Color::BrightMagenta)
.warn(Color::BrightYellow)
.error(Color::BrightRed)
.info(Color::BrightCyan);

let mut dispatch = Dispatch::new();
for output in config.logging.outputs {
dispatch = match output {
LogOutput::File { path } => {
dispatch.chain(create_format_dispatch(None).chain(fern::log_file(path).unwrap()))
}
LogOutput::Stdout { colored } => {
if colored {
dispatch.chain(
create_format_dispatch(Some(logging_colors)).chain(std::io::stdout()),
)
} else {
dispatch.chain(create_format_dispatch(None).chain(std::io::stdout()))
}
}
LogOutput::Stderr { colored } => {
if colored {
dispatch.chain(
create_format_dispatch(Some(logging_colors)).chain(std::io::stderr()),
)
} else {
dispatch.chain(create_format_dispatch(None).chain(std::io::stderr()))
}
}
};
}

dispatch.apply().expect("Couldn't start logger");

if let Some(init_matches) = matches.subcommand_matches("init") {
if config_path.exists() && !init_matches.is_present("force") {
return Err(Error::AlreadyInitialized);
Expand Down Expand Up @@ -145,7 +177,11 @@ async fn main() -> Result<(), Error> {
}
if let Some(_) = matches.subcommand_matches("settings") {
if config_path.exists() {
println!("Configuration location: {}\n\n{}", &config_path.to_str().unwrap(), fs::read_to_string(&config_path).context(OpenConfigFile)?);
println!(
"Configuration location: {}\n\n{}",
&config_path.to_str().unwrap(),
fs::read_to_string(&config_path).context(OpenConfigFile)?
);
} else {
return Err(Error::ConfigurationNotFound);
}
Expand Down Expand Up @@ -178,6 +214,28 @@ fn issue_jwt(secret_key: &str, expiration: Option<DateTime<Utc>>) -> Result<Stri
.context(EncodeJwt)
}

fn create_format_dispatch(colors: Option<ColoredLevelConfig>) -> Dispatch {
Dispatch::new().format(move |out, message, record| {
if let Some(colors) = colors {
out.finish(format_args!(
"{} {} [{}] {}",
Utc::now().format("%Y/%m/%d %H:%M:%S"),
colors.color(record.level()),
record.target(),
message
))
} else {
out.finish(format_args!(
"{} {} [{}] {}",
Utc::now().format("%Y/%m/%d %H:%M:%S"),
record.level(),
record.target(),
message
))
}
})
}

#[derive(Snafu)]
pub enum Error {
#[snafu(display("{}", source))]
Expand Down

0 comments on commit 9ca0fff

Please sign in to comment.