use std::any::Any;
use std::sync::{Arc, Mutex};
use serde_json::{Map, Value, json};
use crate::config::Sent;
use crate::console::{Console, FORMATS, LEVELS, TIMES};
use crate::{Result, Store};
const NAME: &str = "log";
pub(crate) fn follow(store: &Store, console: &Arc<Console>) -> Result<Arc<dyn Any + Send + Sync>> {
let declared = console.declared();
let declaration = json!({
"level": { "kind": "text", "oneOf": one_of(&LEVELS, declared.level), "default": declared.level, "live": true },
"format": { "kind": "text", "oneOf": one_of(&FORMATS, declared.format), "default": declared.format },
"time": { "kind": "text", "oneOf": one_of(&TIMES, declared.time), "default": declared.time },
});
let layers = match &declared.env {
None => json!([]),
Some((prefix, read)) => {
let variables: Map<String, Value> =
read.iter().map(|(name, text)| (name.clone(), Value::String(text.clone()))).collect();
json!([{ "env": { "prefix": prefix, "variables": variables } }])
}
};
let sent = Sent { name: NAME, declaration: &declaration, layers: &layers, strict: false, remember: true };
let config = store.config_sent(&sent)?;
let followed = Arc::clone(console);
let watching = config.watch(move |value, _| {
if let Some(level) = value.get("level").and_then(Value::as_str) {
followed.set_level(level);
}
});
Ok(Arc::new((config, Mutex::new(watching))))
}
fn one_of<T>(table: &[(&'static str, T)], default: &'static str) -> Vec<&'static str> {
let others = table.iter().map(|(name, _)| *name).filter(|name| *name != default);
std::iter::once(default).chain(others).collect()
}
#[cfg(test)]
#[path = "log_config_tests.rs"]
mod tests;