Skip to content

Commit

Permalink
Add an init function which takes a RawConfig (#150)
Browse files Browse the repository at this point in the history
  • Loading branch information
gadunga committed Mar 30, 2020
1 parent a0d19ed commit b5c3894
Showing 1 changed file with 55 additions and 0 deletions.
55 changes: 55 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -189,9 +189,14 @@ use fnv::FnvHasher;
use log::{Level, LevelFilter, Metadata, Record, SetLoggerError};
use std::{cmp, collections::HashMap, hash::BuildHasherDefault, io, io::prelude::*, sync::Arc};

use failure::{Error, Fail};

#[cfg(feature = "config_parsing")]
pub use crate::priv_file::{init_file, load_config_file, FormatError};

#[cfg(feature = "config_parsing")]
pub use crate::config_parsing::{Deserializers, RawConfig};

use crate::{append::Append, config::Config, filter::Filter};

pub mod append;
Expand All @@ -207,6 +212,11 @@ mod priv_file;
#[cfg(feature = "console_writer")]
mod priv_io;

/// Collects the set of errors that occur when deserializing the appenders.
#[derive(Debug, Fail)]
#[fail(display = "Errors on initialization: {:#?}", _0)]
pub struct InitErrors(Vec<Error>);

type FnvHashMap<K, V> = HashMap<K, V, BuildHasherDefault<FnvHasher>>;

struct ConfiguredLogger {
Expand Down Expand Up @@ -418,6 +428,26 @@ pub fn init_config(config: config::Config) -> Result<Handle, SetLoggerError> {
log::set_boxed_logger(Box::new(logger)).map(|()| handle)
}

/// Initializes the global logger as a log4rs logger using the provided raw config.
///
/// This will return errors if the appenders configuration is malformed or if we fail to set the global logger.
#[cfg(feature = "config_parsing")]
pub fn init_raw_config(config: RawConfig) -> Result<(), Error> {
let (appenders, errors) = config.appenders_lossy(&Deserializers::default());
if errors.len() > 0 {
return Err(InitErrors(errors).into());
}
let config = Config::builder()
.appenders(appenders)
.loggers(config.loggers())
.build(config.root())?;
let logger = Logger::new(config);
let logger = Box::new(logger);
log::set_max_level(log::LevelFilter::Info);
log::set_boxed_logger(logger)?;
Ok(())
}

/// A handle to the active logger.
pub struct Handle {
shared: Arc<ArcSwap<SharedLogger>>,
Expand Down Expand Up @@ -450,6 +480,31 @@ mod test {

use super::*;

#[test]
#[cfg(all(feature = "config_parsing", feature = "json_format"))]
#[cfg(target_os = "linux")]
fn init_from_raw_config() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("append.log");

let cfg = format!(
"{{\"refresh_rate\":\"60 seconds\",\"appenders\":{{\"baz\":{{\"kind\":\"file\",\"path\":\"{}\",\"encoder\":{{\"pattern\":\"{{m}}\"}}}}}},\"root\":{{\"appenders\":[\"baz\"],\"level\":\"info\"}}}}",
path.display());
let config = ::serde_json::from_str::<config_parsing::RawConfig>(&cfg).unwrap();
if let Err(e) = init_raw_config(config) {
panic!(e);
}
assert!(path.exists());
log::info!("init_from_raw_config");

let mut contents = String::new();
std::fs::File::open(&path)
.unwrap()
.read_to_string(&mut contents)
.unwrap();
assert_eq!(contents, "init_from_raw_config");
}

#[test]
fn enabled() {
let root = config::Root::builder().build(LevelFilter::Debug);
Expand Down

0 comments on commit b5c3894

Please sign in to comment.