diff --git a/metrics/src/datapoint.rs b/metrics/src/datapoint.rs index 628d475d7f..bbc3f5e693 100644 --- a/metrics/src/datapoint.rs +++ b/metrics/src/datapoint.rs @@ -120,6 +120,19 @@ macro_rules! create_datapoint { (@fields $point:ident) => {}; + // process optional fields + (@fields $point:ident ($name:expr, $value:expr, Option<$type:ident>) , $($rest:tt)*) => { + if let Some(value) = $value { + $crate::create_datapoint!(@field $point $name, value, $type); + } + $crate::create_datapoint!(@fields $point $($rest)*); + }; + (@fields $point:ident ($name:expr, $value:expr, Option<$type:ident>) $(,)?) => { + if let Some(value) = $value { + $crate::create_datapoint!(@field $point $name, value, $type); + } + }; + // process tags (@fields $point:ident $tag_name:expr => $tag_value:expr, $($rest:tt)*) => { $crate::create_datapoint!(@tag $point $tag_name, $tag_value); @@ -261,6 +274,42 @@ mod test { assert_eq!(point.fields[3], ("bool", "true".to_string())); } + #[test] + fn test_optional_datapoint() { + datapoint_debug!("name", ("field name", Some("test"), Option)); + datapoint_info!("name", ("field name", Some(12.34_f64), Option)); + datapoint_trace!("name", ("field name", Some(true), Option)); + datapoint_warn!("name", ("field name", Some(1), Option)); + datapoint_error!("name", ("field name", Some(1), Option),); + datapoint_debug!("name", ("field name", None::, Option)); + datapoint_info!("name", ("field name", None::, Option)); + datapoint_trace!("name", ("field name", None::, Option)); + datapoint_warn!("name", ("field name", None::, Option)); + datapoint_error!("name", ("field name", None::, Option),); + + let point = create_datapoint!( + @point "name", + ("some_i64", Some(1), Option), + ("no_i64", None::, Option), + ("some_String", Some("string space string"), Option), + ("no_String", None::, Option), + ("some_f64", Some(12.34_f64), Option), + ("no_f64", None::, Option), + ("some_bool", Some(true), Option), + ("no_bool", None::, Option), + ); + assert_eq!(point.name, "name"); + assert_eq!(point.tags.len(), 0); + assert_eq!(point.fields[0], ("some_i64", "1i".to_string())); + assert_eq!( + point.fields[1], + ("some_String", "\"string space string\"".to_string()) + ); + assert_eq!(point.fields[2], ("some_f64", "12.34".to_string())); + assert_eq!(point.fields[3], ("some_bool", "true".to_string())); + assert_eq!(point.fields.len(), 4); + } + #[test] fn test_datapoint_with_tags() { datapoint_debug!("name", "tag" => "tag-value", ("field name", "test", String));