slog icon indicating copy to clipboard operation
slog copied to clipboard

is it possible to init OwnedKV by a hashmap?

Open gxxxh opened this issue 9 months ago • 2 comments

the doc's example is

// {{{ Macros
/// Macro for building group of key-value pairs:
/// [`OwnedKV`](struct.OwnedKV.html)
///
/// ```
/// #[macro_use]
/// extern crate slog;
///
/// fn main() {
///     let drain = slog::Discard;
///     let _root = slog::Logger::root(
///         drain,
///         o!("key1" => "value1", "key2" => "value2")
///     );
/// }
/// ```
#[macro_export(local_inner_macros)]
macro_rules! o(
    ($($args:tt)*) => {
        $crate::OwnedKV(kv!($($args)*))
    };
);

but I want to init a hashmap, which may contains a lot of key values, something like o!(key_values), is there any api to use it?

gxxxh avatar Mar 17 '25 03:03 gxxxh

I want a code like this, it seems like the key of function emit_str has to be static

/// Key type
pub type Key = &'static str;

example

struct DynamicKV<'a> {
     map: &'a HashMap<String, String>,
 }

 impl<'a> KV for DynamicKV<'a> {
     fn serialize(&self, _: &Record, s: &mut dyn Serializer) -> slog::Result<()> {
         for (k, v) in self.map.iter() {
             s.emit_str(k, v)?;
         }
         Ok(())
     }
 }

 fn main() {
     let drain = slog::Discard;
     let logger = Logger::root(drain, o!());

     let mut dynamic_pairs = HashMap::new();
     dynamic_pairs.insert("key1".to_string(), "value1".to_string());
     dynamic_pairs.insert("key2".to_string(), "value2".to_string());

     {
         let dynamic_kv = DynamicKV { map: &dynamic_pairs };
         info!(logger, "Dynamic logging"; dynamic_kv);
     }
 }

but it didn't work for this code

gxxxh avatar Mar 17 '25 06:03 gxxxh

There was a feature that would make keys dynamic / CoW. Maybe that would work.

dpc avatar Mar 17 '25 23:03 dpc