🛈 Note: This is pre-release documentation for the upcoming tracing 0.2.0 ecosystem.

For the release documentation, please see docs.rs, instead.

tracing_serde/
fields.rs

1//! Support for serializing fields as `serde` structs or maps.
2use super::*;
3
4#[derive(Debug)]
5pub struct SerializeFieldMap<'a, T>(&'a T);
6
7pub trait AsMap: Sized + sealed::Sealed {
8    fn field_map(&self) -> SerializeFieldMap<'_, Self> {
9        SerializeFieldMap(self)
10    }
11}
12
13impl AsMap for Event<'_> {}
14impl AsMap for Attributes<'_> {}
15impl AsMap for Record<'_> {}
16
17// === impl SerializeFieldMap ===
18
19impl Serialize for SerializeFieldMap<'_, Event<'_>> {
20    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
21    where
22        S: Serializer,
23    {
24        let len = self.0.fields().count();
25        let serializer = serializer.serialize_map(Some(len))?;
26        let mut visitor = SerdeMapVisitor::new(serializer);
27        self.0.record(&mut visitor);
28        visitor.finish()
29    }
30}
31
32impl Serialize for SerializeFieldMap<'_, Attributes<'_>> {
33    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
34    where
35        S: Serializer,
36    {
37        let len = self.0.metadata().fields().len();
38        let serializer = serializer.serialize_map(Some(len))?;
39        let mut visitor = SerdeMapVisitor::new(serializer);
40        self.0.record(&mut visitor);
41        visitor.finish()
42    }
43}
44
45impl Serialize for SerializeFieldMap<'_, Record<'_>> {
46    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
47    where
48        S: Serializer,
49    {
50        let serializer = serializer.serialize_map(None)?;
51        let mut visitor = SerdeMapVisitor::new(serializer);
52        self.0.record(&mut visitor);
53        visitor.finish()
54    }
55}