1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
#![allow(clippy::tabs_in_doc_comments)]
//! `slog_logfmt` - a [`logfmt`](https://brandur.org/logfmt) formatter for slog.
//!
//! This crate exposes a `slog` drain that formats messages as logfmt.
//!
//! # Example
//! ```rust
//! use slog_logfmt::Logfmt;
//! use slog::{debug, o, Drain, Logger};
//! use std::io::stdout;
//!
//! let drain = Logfmt::new(stdout()).build().fuse();
//! let drain = slog_async::Async::new(drain).build().fuse();
//! let logger = Logger::root(drain, o!("logger" => "tests"));
//! debug!(logger, #"tag", "hi there"; "foo" => "bar'baz\"");
//! ```
//!
//! Writes:
//! ```text
//! DEBG | #tag	hi there	logger="tests" foo="bar\'baz\""
//! ```
//!

use slog::{o, Error, Key, OwnedKVList, Record, Value, KV};
use std::borrow::Cow;
use std::cell::RefCell;
use std::fmt::Arguments;
use std::io;

/// A decision on whether to print a key/value pair.
pub enum Redaction {
    /// Print the value as-is.
    Plain,

    /// Do not print the entry at all.
    Skip,

    /// Redact the value with the given function.
    Redact(fn(&'_ dyn Value) -> Arguments),
}

struct Options {
    prefix: fn(&mut dyn io::Write, &Record) -> slog::Result,
    print_level: bool,
    print_msg: bool,
    print_tag: bool,
    force_quotes: bool,
    redactor: fn(&Key) -> Redaction,
}

impl Default for Options {
    fn default() -> Self {
        Options {
            prefix: default_prefix,
            print_level: false,
            print_msg: false,
            print_tag: false,
            force_quotes: false,
            redactor: |_| Redaction::Plain,
        }
    }
}

/// A drain & formatter for [logfmt](https://brandur.org/logfmt)-formatted messages.
///
/// # Format
/// The default format looks like the somewhat-more-human-readable
/// format in https://brandur.org/logfmt#human. You can customize it
/// with the [`LogfmtBuilder`] method `set_prefix`.
pub struct Logfmt<W: io::Write> {
    io: RefCell<W>,
    options: Options,
}

impl<W: io::Write> Logfmt<W> {
    #[allow(clippy::new_ret_no_self)]
    pub fn new(io: W) -> LogfmtBuilder<W> {
        LogfmtBuilder {
            io,
            options: Default::default(),
        }
    }
}

/// A constructor for a [`Logfmt`] drain.
pub struct LogfmtBuilder<W: io::Write> {
    io: W,
    options: Options,
}

impl<W: io::Write> LogfmtBuilder<W> {
    /// Constructs the drain.
    pub fn build(self) -> Logfmt<W> {
        Logfmt {
            io: RefCell::new(self.io),
            options: self.options,
        }
    }

    /// Set a function that prints a (not necessarily
    /// logfmt-formatted) prefix to the output stream.
    pub fn set_prefix(mut self, prefix: fn(&mut dyn io::Write, &Record) -> slog::Result) -> Self {
        self.options.prefix = prefix;
        self
    }

    /// Sets the logger up to print no prefix, effectively starting the line entirely
    /// logfmt field-formatted.
    pub fn no_prefix(mut self) -> Self {
        self.options.prefix = |_, _| Ok(());
        self
    }

    /// Sets a function that makes decisions on whether to log a field.
    ///
    /// This function must return a [`Redaction`] result, which has
    /// two variants at the moment: `Redact::Skip` to not log the
    /// field, and `Redact::Plain` to log the field value in plain
    /// text.
    pub fn redact(mut self, redact: fn(&Key) -> Redaction) -> Self {
        self.options.redactor = redact;
        self
    }

    /// Choose whether to print the log message.
    ///
    /// The default prefix already prints it, so the default is to skip.
    pub fn print_msg(mut self, print: bool) -> Self {
        self.options.print_msg = print;
        self
    }

    /// Choose whether to print the log level.
    ///
    /// The default prefix already prints it, so the default is to skip.
    pub fn print_level(mut self, print: bool) -> Self {
        self.options.print_level = print;
        self
    }

    /// Choose whether to print the log level.
    ///
    /// The default prefix already prints it, so the default is to skip.
    pub fn print_tag(mut self, print: bool) -> Self {
        self.options.print_tag = print;
        self
    }

    /// Force quoting field values even if they don't contain quotable characters.
    ///
    /// Setting this option will surround values with quotes like `foo="bar"`.
    pub fn force_quotes(mut self) -> Self {
        self.options.force_quotes = true;
        self
    }
}

fn default_prefix(io: &mut dyn io::Write, rec: &Record) -> slog::Result {
    let tag_prefix = if rec.tag() == "" { "" } else { "#" };
    let tag_suffix = if rec.tag() == "" { "" } else { "\t" };
    write!(
        io,
        "{level} | {tag_prefix}{tag}{tag_suffix}{msg}\t",
        tag_prefix = tag_prefix,
        tag = rec.tag(),
        tag_suffix = tag_suffix,
        level = rec.level().as_short_str(),
        msg = rec.msg()
    )?;
    Ok(())
}

struct LogfmtSerializer<'a, W: io::Write> {
    io: &'a mut W,
    first: bool,
    force_quotes: bool,
    redactor: fn(&Key) -> Redaction,
}

impl<'a, W: io::Write> LogfmtSerializer<'a, W> {
    fn next_field(&mut self) -> Result<(), io::Error> {
        if self.first {
            self.first = false;
        } else {
            write!(self.io, " ")?;
        }
        Ok(())
    }
}

macro_rules! w(
    ($s:expr, $k:expr, $v:expr) => {{
        use Redaction::*;

        let redact = $s.redactor;
        let val = $v;
        match redact(&$k) {
            Skip => {return Ok(());}
            Plain => {
                $s.next_field()?;
                write!($s.io, "{}={}", $k, val)?;
                Ok(())
            },
            Redact(redactor) => {
                $s.next_field()?;
                let val = format!("{}", redactor(&val));
                write!($s.io, "{}={}", $k, optionally_quote(&val, $s.force_quotes))?;
                Ok(())
            }
        }
    }};
);

fn can_skip_quoting(ch: char) -> bool {
    (ch >= 'a' && ch <= 'z')
        || (ch >= 'A' && ch <= 'Z')
        || (ch >= '0' && ch <= '9')
        || ch == '-'
        || ch == '.'
        || ch == '_'
        || ch == '/'
        || ch == '@'
        || ch == '^'
        || ch == '+'
}

fn optionally_quote(input: &str, force: bool) -> Cow<str> {
    if !force && input.chars().all(can_skip_quoting) {
        input.into()
    } else {
        format!("{:?}", input).into()
    }
}

impl<'a, W> slog::Serializer for LogfmtSerializer<'a, W>
where
    W: io::Write,
{
    fn emit_usize(&mut self, key: slog::Key, val: usize) -> Result<(), Error> {
        w!(self, key, val)
    }

    fn emit_isize(&mut self, key: slog::Key, val: isize) -> Result<(), Error> {
        w!(self, key, val)
    }

    fn emit_bool(&mut self, key: slog::Key, val: bool) -> Result<(), Error> {
        w!(self, key, val)
    }

    fn emit_char(&mut self, key: slog::Key, val: char) -> Result<(), Error> {
        w!(self, key, val)
    }

    fn emit_u8(&mut self, key: slog::Key, val: u8) -> Result<(), Error> {
        w!(self, key, val)
    }

    fn emit_i8(&mut self, key: slog::Key, val: i8) -> Result<(), Error> {
        w!(self, key, val)
    }

    fn emit_u16(&mut self, key: slog::Key, val: u16) -> Result<(), Error> {
        w!(self, key, val)
    }

    fn emit_i16(&mut self, key: slog::Key, val: i16) -> Result<(), Error> {
        w!(self, key, val)
    }

    fn emit_u32(&mut self, key: slog::Key, val: u32) -> Result<(), Error> {
        w!(self, key, val)
    }

    fn emit_i32(&mut self, key: slog::Key, val: i32) -> Result<(), Error> {
        w!(self, key, val)
    }

    fn emit_f32(&mut self, key: slog::Key, val: f32) -> Result<(), Error> {
        w!(self, key, val)
    }

    fn emit_u64(&mut self, key: slog::Key, val: u64) -> Result<(), Error> {
        w!(self, key, val)
    }

    fn emit_i64(&mut self, key: slog::Key, val: i64) -> Result<(), Error> {
        w!(self, key, val)
    }

    fn emit_f64(&mut self, key: slog::Key, val: f64) -> Result<(), Error> {
        w!(self, key, val)
    }

    fn emit_u128(&mut self, key: slog::Key, val: u128) -> Result<(), Error> {
        w!(self, key, val)
    }

    fn emit_i128(&mut self, key: slog::Key, val: i128) -> Result<(), Error> {
        w!(self, key, val)
    }

    fn emit_str(&mut self, key: slog::Key, val: &str) -> Result<(), Error> {
        let val = optionally_quote(val, self.force_quotes);
        w!(self, key, &*val)
    }

    fn emit_unit(&mut self, key: slog::Key) -> Result<(), Error> {
        w!(self, key, "()")
    }

    fn emit_none(&mut self, key: slog::Key) -> Result<(), Error> {
        w!(self, key, "None")
    }

    fn emit_arguments<'b>(&mut self, key: slog::Key, val: &Arguments<'b>) -> Result<(), Error> {
        let val = format!("{}", val);
        let val = optionally_quote(&val, self.force_quotes);
        w!(self, key, &*val)
    }
}

impl<W> slog::Drain for Logfmt<W>
where
    W: io::Write,
{
    type Ok = ();
    type Err = io::Error;

    fn log<'a>(
        &self,
        record: &Record<'a>,
        logger_values: &OwnedKVList,
    ) -> Result<Self::Ok, Self::Err> {
        let mut io = self.io.borrow_mut();
        let prefix = self.options.prefix;
        prefix(&mut *io, record)?;

        let mut serializer = LogfmtSerializer {
            io: &mut *io,
            first: true,
            force_quotes: self.options.force_quotes,
            redactor: self.options.redactor,
        };
        if self.options.print_level {
            let lvl = o!("level" => record.level().as_short_str());
            lvl.serialize(record, &mut serializer)?;
        }
        if self.options.print_msg {
            record.msg().serialize(
                record,
                #[allow(clippy::identity_conversion)] // necessary for dynamic-keys
                "msg".into(),
                &mut serializer,
            )?;
        }
        if self.options.print_tag {
            let tag = o!("level" => record.tag());
            tag.serialize(record, &mut serializer)?;
        }
        logger_values.serialize(record, &mut serializer)?;
        record.kv().serialize(record, &mut serializer)?;

        io.write_all(b"\n")?;
        io.flush()?;

        Ok(())
    }
}