Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Make RawConfig serializable #383

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions src/append/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
use log::{Log, Record};
#[cfg(feature = "config_parsing")]
use serde::{de, Deserialize, Deserializer};
use serde::{Serialize, Serializer};
#[cfg(feature = "config_parsing")]
use serde_value::Value;
#[cfg(feature = "config_parsing")]
Expand Down Expand Up @@ -151,6 +152,46 @@ impl<'de> Deserialize<'de> for AppenderConfig {
}
}

#[cfg(feature = "config_parsing")]
impl Serialize for AppenderConfig {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut map: BTreeMap<Value, Value> = BTreeMap::new();

map.insert(
Value::String("kind".to_string()),
Value::String(self.kind.clone()),
);

// Insert the `filters` field into the map if it's not empty
if !self.filters.is_empty() {
let filters: Vec<Value> = self
.filters
.iter()
.map(|f| serde_value::to_value(f).unwrap())
.collect();

map.insert(Value::String("filters".to_string()), Value::Seq(filters));
} else {
map.insert(
Value::String("filters".to_string()),
Value::String("[]".to_string()),
);
}

if let Value::Map(ref config_map) = self.config {
for (key, value) in config_map {
map.insert(key.clone(), value.clone());
}
}

// Serialize the map
map.serialize(serializer)
}
}

#[cfg(test)]
mod test {
#[cfg(any(feature = "file_appender", feature = "rolling_file_appender"))]
Expand Down
65 changes: 46 additions & 19 deletions src/config/raw.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,8 +94,12 @@ use std::{collections::HashMap, fmt, marker::PhantomData, sync::Arc, time::Durat
use anyhow::anyhow;
use derivative::Derivative;
use log::LevelFilter;
use serde::de::{self, Deserialize as SerdeDeserialize, DeserializeOwned};
use serde::{
de::{self, Deserialize as SerdeDeserialize, DeserializeOwned},
ser,
};
use serde_value::Value;

use thiserror::Error;
use typemap_ors::{Key, ShareCloneMap};

Expand Down Expand Up @@ -318,10 +322,11 @@ pub enum DeserializingConfigError {
}

/// A raw deserializable log4rs configuration.
#[derive(Clone, Debug, Default, serde::Deserialize)]
#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)]
#[serde(deny_unknown_fields)]
pub struct RawConfig {
#[serde(deserialize_with = "de_duration", default)]
#[serde(serialize_with = "ser_duration")]
refresh_rate: Option<Duration>,

#[serde(default)]
Expand Down Expand Up @@ -403,6 +408,19 @@ impl RawConfig {
}
}

fn ser_duration<S>(duration: &Option<Duration>, s: S) -> Result<S::Ok, S::Error>
where
S: ser::Serializer,
{
match duration {
Some(duration) => {
let duration_str: String = humantime::format_duration(*duration).to_string();
s.serialize_some(&duration_str)
}
None => s.serialize_none(),
}
}

fn de_duration<'de, D>(d: D) -> Result<Option<Duration>, D::Error>
where
D: de::Deserializer<'de>,
Expand Down Expand Up @@ -438,7 +456,7 @@ where
Option::<S>::deserialize(d).map(|r| r.map(|s| s.0))
}

#[derive(Clone, Debug, Derivative, serde::Deserialize)]
#[derive(Clone, Debug, Derivative, serde::Deserialize, serde::Serialize)]
#[derivative(Default)]
#[serde(deny_unknown_fields)]
struct Root {
Expand All @@ -453,7 +471,7 @@ fn root_level_default() -> LevelFilter {
LevelFilter::Debug
}

#[derive(serde::Deserialize, Debug, Clone)]
#[derive(serde::Deserialize, Debug, Clone, serde::Serialize)]
#[serde(deny_unknown_fields)]
struct Logger {
level: LevelFilter,
Expand All @@ -470,16 +488,14 @@ fn logger_additive_default() -> bool {
#[cfg(test)]
#[allow(unused_imports)]
mod test {
use std::fs;

use super::*;
use std::fs;

#[test]
#[cfg(all(feature = "yaml_format", feature = "threshold_filter"))]
fn full_deserialize() {
let cfg = r#"
refresh_rate: 60 seconds

const CFG: &'static str = r#"refresh_rate: 1m
root:
level: info
appenders:
- console
appenders:
console:
kind: console
Expand All @@ -491,25 +507,36 @@ appenders:
path: /tmp/baz.log
encoder:
pattern: "%m"

root:
appenders:
- console
level: info

loggers:
foo::bar::baz:
level: warn
appenders:
- baz
additive: false
"#;
let config = ::serde_yaml::from_str::<RawConfig>(cfg).unwrap();

#[test]
#[cfg(all(feature = "yaml_format", feature = "threshold_filter"))]
fn full_deserialize() {
let config = ::serde_yaml::from_str::<RawConfig>(CFG).unwrap();
let errors = config.appenders_lossy(&Deserializers::new()).1;
println!("{:?}", errors);
assert!(errors.is_empty());
}

#[test]
#[cfg(all(feature = "yaml_format", feature = "threshold_filter"))]
fn full_serialize() {
let config = ::serde_yaml::from_str::<RawConfig>(CFG).unwrap();
let errors = config.appenders_lossy(&Deserializers::new()).1;
println!("{:?}", errors);
assert!(errors.is_empty());

let config = ::serde_yaml::to_string::<RawConfig>(&config);

assert_eq!(config.unwrap(), CFG)
}

#[test]
#[cfg(feature = "yaml_format")]
fn empty() {
Expand Down
25 changes: 24 additions & 1 deletion src/filter/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

use log::Record;
#[cfg(feature = "config_parsing")]
use serde::de;
use serde::{de, Serialize, Serializer};
#[cfg(feature = "config_parsing")]
use serde_value::Value;
#[cfg(feature = "config_parsing")]
Expand Down Expand Up @@ -80,6 +80,29 @@ impl<'de> de::Deserialize<'de> for FilterConfig {
}
}

#[cfg(feature = "config_parsing")]
impl Serialize for FilterConfig {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut map = BTreeMap::new();

map.insert(
Value::String("kind".to_owned()),
Value::String(self.kind.clone()),
);

if let Value::Map(ref config_map) = self.config {
for (key, value) in config_map {
map.insert(key.clone(), value.clone());
}
}

map.serialize(serializer)
}
}

#[cfg(test)]
mod test {
#[cfg(feature = "config_parsing")]
Expand Down