Files
feroxbuster/src/logger.rs

82 lines
2.6 KiB
Rust
Raw Permalink Normal View History

2021-01-19 08:35:56 -06:00
use std::env;
use std::fs::OpenOptions;
2021-01-30 20:43:31 -06:00
use std::io::BufWriter;
use std::sync::{Arc, RwLock};
2021-01-19 08:35:56 -06:00
use std::time::Instant;
2021-01-30 20:43:31 -06:00
use anyhow::{Context, Result};
2021-01-19 08:35:56 -06:00
use env_logger::Builder;
use crate::{
config::Configuration,
message::FeroxMessage,
progress::PROGRESS_PRINTER,
2021-02-03 10:39:54 -06:00
traits::FeroxSerialize,
utils::{fmt_err, write_to},
};
2020-08-28 15:58:29 -05:00
/// Create a customized instance of
/// [env_logger::Logger](https://docs.rs/env_logger/latest/env_logger/struct.Logger.html)
/// with timer offset/color and set the log level based on `verbosity`
2021-01-29 20:04:59 -06:00
pub fn initialize(config: Arc<Configuration>) -> Result<()> {
// use occurrences of -v on commandline to or verbosity = N in feroxconfig.toml to set
// log level for the application; respects already specified RUST_LOG environment variable
match env::var("RUST_LOG") {
2021-01-05 13:36:19 -06:00
Ok(_) => {} // RUST_LOG found, don't override
Err(_) => {
// only set log level based on verbosity when RUST_LOG variable doesn't exist
2021-01-29 20:04:59 -06:00
match config.verbosity {
0 => (),
1 => env::set_var("RUST_LOG", "warn"),
2 => env::set_var("RUST_LOG", "info"),
2020-11-14 15:34:18 -06:00
3 => env::set_var("RUST_LOG", "feroxbuster=debug,info"),
_ => env::set_var("RUST_LOG", "feroxbuster=trace,info"),
}
}
}
2020-08-28 15:58:29 -05:00
let start = Instant::now();
let mut builder = Builder::from_default_env();
2021-01-29 20:04:59 -06:00
let file = if !config.debug_log.is_empty() {
2021-01-19 08:35:56 -06:00
let f = OpenOptions::new() // std fs
.create(true)
.append(true)
2021-01-29 20:04:59 -06:00
.open(&config.debug_log)
.with_context(|| fmt_err(&format!("Could not open {}", &config.debug_log)))?;
2021-01-19 08:35:56 -06:00
let mut writer = BufWriter::new(f);
// write out the configuration to the debug file if it exists
2021-01-29 20:04:59 -06:00
write_to(&*config, &mut writer, config.json)?;
2021-01-19 08:35:56 -06:00
Some(Arc::new(RwLock::new(writer)))
} else {
None
};
2020-08-28 15:58:29 -05:00
builder
.format(move |_, record| {
let log_entry = FeroxMessage {
message: record.args().to_string(),
level: record.level().to_string(),
time_offset: start.elapsed().as_secs_f32(),
module: record.target().to_string(),
kind: "log".to_string(),
};
2022-12-29 15:32:22 -06:00
PROGRESS_PRINTER.println(log_entry.as_str());
2021-01-19 08:35:56 -06:00
if let Some(buffered_file) = file.clone() {
if let Ok(mut unlocked) = buffered_file.write() {
2021-01-29 20:04:59 -06:00
let _ = write_to(&log_entry, &mut unlocked, config.json);
2021-01-19 08:35:56 -06:00
}
}
Ok(())
2020-08-28 15:58:29 -05:00
})
.init();
2021-01-19 08:35:56 -06:00
Ok(())
2020-08-28 15:58:29 -05:00
}