Skip to content

Commit

Permalink
Add more logging configuration
Browse files Browse the repository at this point in the history
  • Loading branch information
shuni64 committed Jan 23, 2020
1 parent 8f6cd38 commit f7464f5
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 25 deletions.
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
91 changes: 66 additions & 25 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 @@ -25,7 +25,6 @@ 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 @@ -58,29 +57,6 @@ const CREDITS: &'static str = "\

#[tokio::main]
async fn main() -> Result<(), Error> {
let logging_colors = ColoredLevelConfig::new()
.debug(Color::BrightMagenta)
.warn(Color::BrightYellow)
.error(Color::BrightRed)
.info(Color::BrightCyan);

Dispatch::new()
.format(move |out, message, record| {
out.finish(format_args!(
"{} {} [{}] {}",
Utc::now().format("%Y/%m/%d %H:%M:%S"),
logging_colors.color(record.level()),
record.target(),
message
))
})
.chain(std::io::stdout())
.chain(fern::log_file("output.log").unwrap())
// .chain(syslog::unix(syslog_formatter)) // Commented for now, it don't compile for an unknown reason
.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!(),
Expand Down Expand Up @@ -125,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 @@ -195,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 f7464f5

Please sign in to comment.