Skip to main content

systemprompt_logging/services/
format.rs

1use std::fmt::{self, Write};
2use tracing::field::{Field, Visit};
3use tracing_subscriber::field::{MakeVisitor, VisitFmt, VisitOutput};
4use tracing_subscriber::fmt::format::Writer;
5
6#[derive(Debug, Clone, Copy, Default)]
7pub struct FilterSystemFields;
8
9impl FilterSystemFields {
10    pub const fn new() -> Self {
11        Self
12    }
13}
14
15#[derive(Debug)]
16pub struct FilteringVisitor<'a> {
17    writer: Writer<'a>,
18    is_first: bool,
19    result: fmt::Result,
20}
21
22impl<'a> FilteringVisitor<'a> {
23    const fn new(writer: Writer<'a>) -> Self {
24        Self {
25            writer,
26            is_first: true,
27            result: Ok(()),
28        }
29    }
30
31    fn record_filtered(&mut self, field: &Field, value: &dyn fmt::Debug) {
32        if self.result.is_err() {
33            return;
34        }
35
36        let debug_str = format!("{:?}", value);
37        if debug_str == "\"system\"" || debug_str == "system" {
38            return;
39        }
40
41        self.result = self.write_field(field.name(), &debug_str);
42    }
43
44    fn write_field(&mut self, name: &str, value: &str) -> fmt::Result {
45        if self.is_first {
46            self.is_first = false;
47        } else {
48            self.writer.write_char(' ')?;
49        }
50        write!(self.writer, "{}={}", name, value)
51    }
52}
53
54impl Visit for FilteringVisitor<'_> {
55    fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) {
56        self.record_filtered(field, value);
57    }
58
59    fn record_str(&mut self, field: &Field, value: &str) {
60        if self.result.is_err() {
61            return;
62        }
63        if value == "system" {
64            return;
65        }
66        self.result = self.write_field(field.name(), &format!("{:?}", value));
67    }
68}
69
70impl VisitOutput<fmt::Result> for FilteringVisitor<'_> {
71    fn finish(self) -> fmt::Result {
72        self.result
73    }
74}
75
76impl VisitFmt for FilteringVisitor<'_> {
77    fn writer(&mut self) -> &mut dyn Write {
78        &mut self.writer
79    }
80}
81
82impl<'a> MakeVisitor<Writer<'a>> for FilterSystemFields {
83    type Visitor = FilteringVisitor<'a>;
84
85    fn make_visitor(&self, target: Writer<'a>) -> Self::Visitor {
86        FilteringVisitor::new(target)
87    }
88}