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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
//! Html formatter for `slog-rs`
//!
//! # Examples
//!
//! Writing logs to an HTML file
//!
//! ```
//! #[macro_use]
//! extern crate slog;
//! extern crate slog_html;
//! extern crate slog_stream;
//!
//! use slog::DrainExt;
//!
//! use std::fs::OpenOptions;
//!
//! fn main() {
//!     let file = OpenOptions::new()
//!         .create(true)
//!         .write(true)
//!         .truncate(true)
//!         .open("target/log.html").unwrap();
//!
//!     let log = slog::Logger::root(
//!         slog_stream::stream(
//!             file,
//!             slog_html::default()
//!         ).fuse(),
//!         o!("version" => env!("CARGO_PKG_VERSION"))
//!     );
//!
//!     debug!(log, "debug values"; "x" => 1, "y" => -1);
//! }
//! ```
//!
//! Create HTML logger with custom options
//!
//! Use a greyscale color palette for the log levels and disable boldness for the message part.
//!
//! ```
//! # #[macro_use]
//! # extern crate slog;
//! # extern crate slog_html;
//! # extern crate slog_stream;
//! #
//! # use slog::DrainExt;
//! #
//! # use std::fs::OpenOptions;
//! #
//! # fn main() {
//! #     let file = OpenOptions::new()
//! #         .create(true)
//! #         .write(true)
//! #         .truncate(true)
//! #         .open("target/log.html").unwrap();
//! #
//! #     let log = slog::Logger::root(
//! #         slog_stream::stream(
//! #             file,
//!             slog_html::new()
//!                 .compact()
//!                 .color_palette(slog_html::ColorPalette {
//!                     critical: "000000",
//!                     error: "1e1e1e",
//!                     warning: "3c3c3c",
//!                     info: "5a5a5a",
//!                     debug: "787878",
//!                     trace: "969696",
//!                 })
//!                 .message_style(slog_html::Style {
//!                     bold: false,
//!                     .. slog_html::Style::default()
//!                 })
//!                 .build()
//! #         ).fuse(),
//! #         o!("version" => env!("CARGO_PKG_VERSION"))
//! #     );
//! #
//! #     debug!(log, "debug values"; "x" => 1, "y" => -1);
//! # }
//! ```
#![warn(missing_docs)]

#[macro_use]
extern crate slog;
extern crate slog_stream;
extern crate chrono;

mod decorator;
mod serializer;
mod color_palette;
mod style;

use std::io;
use std::sync::Mutex;

use slog::Record;
use slog::OwnedKeyValueList;
use slog_stream::{Decorator, RecordDecorator};

use decorator::HtmlDecorator;
use serializer::Serializer;
use style::StyleTable;
pub use style::Style;
pub use color_palette::ColorPalette;

/// Formatting mode
pub enum FormatMode {
    /// Compact logging format
    Compact,
    /// Full logging format
    Full,
}

/// Html formatter
pub struct Format<D: Decorator> {
    mode: FormatMode,
    value_stack: Mutex<Vec<Vec<u8>>>,
    decorator: D,
    fn_timestamp: Box<TimestampFn>,
}

impl<D: Decorator> Format<D> {
    /// Create a new Html formatter
    pub fn new(mode: FormatMode, decorator: D, fn_timestamp: Box<TimestampFn>) -> Self {
        Format {
            mode: mode,
            value_stack: Mutex::new(Vec::new()),
            decorator: decorator,
            fn_timestamp: fn_timestamp,
        }
    }

    fn format_full(&self,
                   io: &mut io::Write,
                   record: &Record,
                   logger_values: &OwnedKeyValueList)
                   -> io::Result<()> {

        let r_decorator = self.decorator.decorate(record);

        try!(io.write_all(b"<pre style=\"margin-bottom:-0.5em\">"));

        try!(r_decorator.fmt_timestamp(io, &*self.fn_timestamp));
        try!(r_decorator.fmt_level(io, &|io| write!(io, " {} ", record.level().as_short_str())));
        try!(r_decorator.fmt_msg(io, &|io| write!(io, "{}", record.msg())));

        let mut serializer = Serializer::new(io, r_decorator);

        for (k, v) in logger_values.iter() {
            try!(serializer.print_comma());
            try!(v.serialize(record, k, &mut serializer));
        }

        for &(k, v) in record.values().iter() {
            try!(serializer.print_comma());
            try!(v.serialize(record, k, &mut serializer));
        }

        let (mut io, _) = serializer.finish();

        io.write_all(b"</pre>\n")
    }

    fn format_compact(&self,
                      io: &mut io::Write,
                      record: &Record,
                      logger_values: &OwnedKeyValueList)
                      -> io::Result<()> {

        let mut value_stack = self.value_stack.lock().expect("failed to lock value_stack");
        let mut record_value_stack = try!(self.record_value_stack(record, logger_values));
        record_value_stack.reverse();
        let indent = record_value_stack.len();

        let mut changed = false;
        for i in 0..record_value_stack.len() {
            if value_stack.len() <= i || value_stack[i] != record_value_stack[i] {
                changed = true;
            }

            if changed {
                try!(io.write_all(b"<pre style=\"margin-bottom:-0.5em\">"));
                try!(self.print_indent(io, i));
                try!(io.write_all(&record_value_stack[i]));
                try!(io.write_all(b"</pre>\n"));
            }
        }
        if changed || value_stack.len() != record_value_stack.len() {
            *value_stack = record_value_stack;
        }

        let r_decorator = self.decorator.decorate(record);

        try!(io.write_all(b"<pre style=\"margin-bottom:-0.5em\">"));

        try!(self.print_indent(io, indent));
        try!(r_decorator.fmt_timestamp(io, &*self.fn_timestamp));
        try!(r_decorator.fmt_level(io, &|io| write!(io, " {} ", record.level().as_short_str())));
        try!(r_decorator.fmt_msg(io, &|io| write!(io, "{}", record.msg())));

        let mut serializer = Serializer::new(io, r_decorator);

        for &(k, v) in record.values().iter() {
            try!(serializer.print_comma());
            try!(v.serialize(record, k, &mut serializer));
        }

        let (mut io, _) = serializer.finish();

        io.write_all(b"</pre>\n")
    }

    /// Get formatted record_value_stack from `logger_values_ref`
    fn record_value_stack(&self,
                          record: &slog::Record,
                          logger_values_ref: &slog::OwnedKeyValueList)
                          -> io::Result<Vec<Vec<u8>>> {

        let mut value_stack = if let Some(logger_values) = logger_values_ref.values() {
            let r_decorator = self.decorator.decorate(record);
            let buf: Vec<u8> = Vec::with_capacity(128);
            let mut serializer = Serializer::new(buf, r_decorator);

            let mut clean = true;
            let mut logger_values = logger_values;
            loop {
                let (k, v) = logger_values.head();
                if !clean {
                    try!(serializer.print_comma());
                }
                try!(v.serialize(record, k, &mut serializer));
                clean = false;
                logger_values = if let Some(v) = logger_values.tail() {
                    v
                } else {
                    break;
                }
            }
            let (buf, _) = serializer.finish();
            vec![buf]
        } else {
            Vec::new()
        };

        if let Some(ref parent) = *logger_values_ref.parent() {
            let mut value = try!(self.record_value_stack(record, parent));
            value_stack.append(&mut value);
        }

        Ok(value_stack)
    }

    fn print_indent(&self, io: &mut io::Write, indent: usize) -> io::Result<()> {
        for _ in 0..indent {
            try!(write!(io, "  "));
        }
        Ok(())
    }
}

impl<D: Decorator> slog_stream::Format for Format<D> {
    fn format(&self,
              io: &mut io::Write,
              record: &Record,
              logger_values: &OwnedKeyValueList)
              -> io::Result<()> {
        match self.mode {
            FormatMode::Compact => self.format_compact(io, record, logger_values),
            FormatMode::Full => self.format_full(io, record, logger_values),
        }
    }
}

/// Timestamp function type
pub type TimestampFn = Fn(&mut io::Write) -> io::Result<()> + Send + Sync;

const TIMESTAMP_FORMAT: &'static str = "%b %d %H:%M:%S%.3f";

/// Default local timestamp function used by `Format`
///
/// The exact format used, is still subject to change.
pub fn timestamp_local(io: &mut io::Write) -> io::Result<()> {
    write!(io, "{}", chrono::Local::now().format(TIMESTAMP_FORMAT))
}

/// Default UTC timestamp function used by `Format`
///
/// The exact format used, is still subject to change.
pub fn timestamp_utc(io: &mut io::Write) -> io::Result<()> {
    write!(io, "{}", chrono::UTC::now().format(TIMESTAMP_FORMAT))
}

/// Streamer builder
pub struct FormatBuilder {
    mode: FormatMode,
    color_palette: ColorPalette,
    style: StyleTable,
    fn_timestamp: Box<TimestampFn>,
}

impl FormatBuilder {
    /// New `FormatBuilder`
    fn new() -> Self {
        FormatBuilder {
            mode: FormatMode::Full,
            color_palette: ColorPalette::default(),
            style: StyleTable::default(),
            fn_timestamp: Box::new(timestamp_local),
        }
    }

    /// Output using full mode (default)
    pub fn full(mut self) -> Self {
        self.mode = FormatMode::Full;
        self
    }

    /// Output using compact mode
    pub fn compact(mut self) -> Self {
        self.mode = FormatMode::Compact;
        self
    }

    /// Use custom color palette
    pub fn color_palette(mut self, color_palette: ColorPalette) -> Self {
        self.color_palette = color_palette;
        self
    }

    /// Use custom style for the log level
    pub fn level_style(mut self, style: Style) -> Self {
        self.style.level = style;
        self
    }

    /// Use custom style for the timestamp
    pub fn timestamp_style(mut self, style: Style) -> Self {
        self.style.timestamp = style;
        self
    }

    /// Use custom style for the message
    pub fn message_style(mut self, style: Style) -> Self {
        self.style.message = style;
        self
    }

    /// Use custom style for keys
    pub fn key_style(mut self, style: Style) -> Self {
        self.style.key = style;
        self
    }

    /// Use custom style for values
    pub fn value_style(mut self, style: Style) -> Self {
        self.style.value = style;
        self
    }

    /// Use custom style for separators
    pub fn separator_style(mut self, style: Style) -> Self {
        self.style.separator = style;
        self
    }

    /// Use the UTC time zone for the timestamp
    pub fn use_utc_timestamp(mut self) -> Self {
        self.fn_timestamp = Box::new(timestamp_utc);
        self
    }

    /// Use the local time zone for the timestamp (default)
    pub fn use_local_timestamp(mut self) -> Self {
        self.fn_timestamp = Box::new(timestamp_local);
        self
    }

    /// Provide a custom function to generate the timestamp
    pub fn use_custom_timestamp<F>(mut self, f: F) -> Self
        where F: Fn(&mut io::Write) -> io::Result<()> + 'static + Send + Sync
    {
        self.fn_timestamp = Box::new(f);
        self
    }

    /// Build Html formatter
    pub fn build(self) -> Format<HtmlDecorator> {
        Format {
            mode: self.mode,
            value_stack: Mutex::new(Vec::new()),
            decorator: HtmlDecorator::new(self.color_palette, self.style),
            fn_timestamp: self.fn_timestamp,
        }
    }
}

impl Default for FormatBuilder {
    fn default() -> Self {
        Self::new()
    }
}

/// Create new `FormatBuilder` to create `Format`
pub fn new() -> FormatBuilder {
    FormatBuilder::new()
}

/// Default html `Format`
pub fn default() -> Format<HtmlDecorator> {
    FormatBuilder::new().build()
}