logforth_layout_logfmt/
lib.rs

1// Copyright 2024 FastLabs Developers
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! A logfmt layout for formatting log records.
16
17#![cfg_attr(docsrs, feature(doc_cfg))]
18
19use jiff::Timestamp;
20use jiff::tz::TimeZone;
21use logforth_core::Diagnostic;
22use logforth_core::Error;
23use logforth_core::kv::Key;
24use logforth_core::kv::Value;
25use logforth_core::kv::Visitor;
26use logforth_core::layout::Layout;
27use logforth_core::record::Record;
28
29/// A logfmt layout for formatting log records.
30///
31/// Output format:
32///
33/// ```text
34/// timestamp=2025-03-31T21:04:28.986032+08:00 level=TRACE module=rs_log position=main.rs:22 message="Hello trace!"
35/// timestamp=2025-03-31T21:04:28.991233+08:00 level=DEBUG module=rs_log position=main.rs:23 message="Hello debug!"
36/// timestamp=2025-03-31T21:04:28.991239+08:00 level=INFO module=rs_log position=main.rs:24 message="Hello info!"
37/// timestamp=2025-03-31T21:04:28.991273+08:00 level=WARN module=rs_log position=main.rs:25 message="Hello warn!"
38/// timestamp=2025-03-31T21:04:28.991277+08:00 level=ERROR module=rs_log position=main.rs:26 message="Hello err!"
39/// ```
40///
41/// # Examples
42///
43/// ```
44/// use logforth_layout_logfmt::LogfmtLayout;
45///
46/// let layout = LogfmtLayout::default();
47/// ```
48#[derive(Default, Debug, Clone)]
49pub struct LogfmtLayout {
50    tz: Option<TimeZone>,
51}
52
53impl LogfmtLayout {
54    /// Set the timezone for timestamps.
55    ///
56    /// # Examples
57    ///
58    /// ```
59    /// use jiff::tz::TimeZone;
60    /// use logforth_layout_logfmt::LogfmtLayout;
61    ///
62    /// let layout = LogfmtLayout::default().timezone(TimeZone::UTC);
63    /// ```
64    pub fn timezone(mut self, tz: TimeZone) -> Self {
65        self.tz = Some(tz);
66        self
67    }
68}
69
70struct KvFormatter {
71    text: String,
72}
73
74impl Visitor for KvFormatter {
75    // The encode logic is copied from https://github.com/go-logfmt/logfmt/blob/76262ea7/encode.go.
76    fn visit(&mut self, key: Key, value: Value) -> Result<(), Error> {
77        use std::fmt::Write;
78
79        let key = key.as_str();
80        let value = value.to_string();
81        let value = value.as_str();
82
83        if key.contains([' ', '=', '"']) {
84            // omit keys contain special chars
85            return Err(Error::new(format!("key contains special chars: {key}")));
86        }
87
88        // SAFETY: write to a string always succeeds
89        if value.contains([' ', '=', '"']) {
90            write!(&mut self.text, " {key}=\"{}\"", value.escape_debug()).unwrap();
91        } else {
92            write!(&mut self.text, " {key}={value}").unwrap();
93        }
94
95        Ok(())
96    }
97}
98
99impl Layout for LogfmtLayout {
100    fn format(&self, record: &Record, diags: &[Box<dyn Diagnostic>]) -> Result<Vec<u8>, Error> {
101        // SAFETY: jiff::Timestamp::try_from only fails if the time is out of range, which is
102        // very unlikely if the system clock is correct.
103        let ts = Timestamp::try_from(record.time()).unwrap();
104        let tz = self.tz.clone().unwrap_or_else(TimeZone::system);
105        let offset = tz.to_offset(ts);
106        let time = ts.display_with_offset(offset);
107
108        let level = record.level();
109        let target = record.target();
110        let file = record.filename();
111        let line = record.line().unwrap_or_default();
112        let message = record.payload();
113
114        let mut visitor = KvFormatter {
115            text: format!("timestamp={time:.6}"),
116        };
117
118        visitor.visit(Key::new("level"), level.as_str().into())?;
119        visitor.visit(Key::new("module"), target.into())?;
120        visitor.visit(
121            Key::new("position"),
122            Value::from_display(&format_args!("{file}:{line}")),
123        )?;
124        visitor.visit(Key::new("message"), Value::from_str(message))?;
125
126        record.key_values().visit(&mut visitor)?;
127        for d in diags {
128            d.visit(&mut visitor)?;
129        }
130
131        Ok(visitor.text.into_bytes())
132    }
133}