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
use super::logger::RecordInfo;
use super::ser::{SerdeSerializer};
use super::Level;

use super::{BorrowedKeyValue,OwnedKeyValue};
use std::fmt::Write;

use serde_json;
use ansi_term::Colour;

/// Format record information
pub trait Format : Send+Sync+Sized {
    /// Format one logging record into `String`
    fn format(&self, info : &RecordInfo, logger_values : &[OwnedKeyValue], record_values : &[BorrowedKeyValue]) -> String;
}


/// ToJson formatter
///
/// Each record will be printed as a Json map.
pub struct Json {
    newlines : bool,
    values : Vec<OwnedKeyValue>,
}


impl Json {
    /// Create new `Json` format.
    ///
    /// TODO: Add a builder pattern to configure newlines,
    /// and custom records.
    pub fn new() -> Self {
        Json {
            newlines : true,
            values : o!(
                "ts" => |rinfo : &RecordInfo| {
                    rinfo.ts.to_rfc3339()
                },
                "level" => |rinfo : &RecordInfo| {
                    rinfo.level.as_str()
                },
                "msg" => |rinfo : &RecordInfo| {
                    rinfo.msg.clone()
                }
                ).to_vec()
        }
    }

    /// Create new `Json` format that does not add
    /// newlines after each record.
    pub fn new_nonewline() -> Self {
        let mut json = Json::new();
        json.newlines = false;
        json
    }
}

impl Format for Json {
    fn format(&self, rinfo : &RecordInfo, logger_values : &[OwnedKeyValue], record_values : &[BorrowedKeyValue]) -> String {
        let mut serializer = serde_json::Serializer::new(vec!());
        {
            let mut serializer = &mut SerdeSerializer(&mut serializer);
            for &(ref k, ref v) in self.values.iter() {
                v.serialize(rinfo, k, serializer);
            }
            for &(ref k, ref v) in logger_values.iter() {
                v.serialize(rinfo, k, serializer);
            }

            for &(ref k, ref v) in record_values.iter() {
                v.serialize(rinfo, k, serializer);
            }
        }

        // TODO: Optimize this part
        let mut inner_bytes = serializer.into_inner();
        {
            let empty = inner_bytes.is_empty();
            if empty {
                inner_bytes.push(',' as u8);
            }
        }
        let inner_str = String::from_utf8_lossy(&inner_bytes);

        if self.newlines {
            format!("{{{}}}\n", &inner_str[1..])
        } else {
            format!("{{{}}}", &inner_str[1..])
        }
    }
}

/// Terminal formatting with optional color support
pub struct Terminal {
    color : bool,
}

impl Terminal {
    /// New Terminal format that prints using color
    pub fn colored() -> Self {
        Terminal {
            color: true,
        }
    }

    /// New Terminal format that prints without using color
    pub fn plain() -> Self {
        Terminal {
            color: false,
        }
    }
}

fn severity_to_color(lvl : Level) -> u8 {
    match lvl {
        Level::Critical => 35,
        Level::Error => 31,
        Level::Warning => 33,
        Level::Info => 32,
        Level::Debug => 36,
        Level::Trace => 0,
    }
}

impl Format for Terminal {
    fn format(&self, info : &RecordInfo, logger_values : &[OwnedKeyValue], values : &[BorrowedKeyValue]) -> String {
        let color = Colour::Fixed(severity_to_color(info.level));

        let mut s = String::new();

        let _ = write!(s, "{:?}[{}] {}",
               info.ts,
               if self.color {
                   color.paint(info.level.as_str()).to_string()
               } else {
                   info.level.as_str().to_owned()
               },
               info.msg
               );


        for &(ref k, ref v) in logger_values {
            let _ = write!(s, ", ");
            v.serialize(info, k, &mut s);
        }

        for &(k,v) in values {
            let _ = write!(s, ", ");
            v.serialize(info, k, &mut s);
        }

        s.push_str("\n");

        s
    }
}