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
//! `json_env_logger` is an extension of [`env_logger`](https://crates.io/crates/env_logger) crate providing JSON formatted logs.
//!
//! The [`env_logger`](https://crates.io/crates/env_logger) is a crate that provides a way to declare what log levels are enabled for which modules \via a `RUST_LOG` env variable. See its documentation for
//! syntax of declaring crate and module filtering options.
//!
//! ## features
//!
//! * `iso-timestamps`
//!
//! By default, a timestamp field called `ts` is emitted with the current unix epic timestamp in seconds
//! You can replace this with IOS-8601 timestamps by enabling the `iso-timestamps` feature. Note, this will add `chrono` crate
//! to your dependency tree.
//!
//! ```toml
//! [dependencies]
//! json_env_logger = { version = "0.1", features = ["iso-timestamps"] }
//! ```
//! * `backtrace`
//!
//! When registering a panic hook with `panic_hook` by default backtraces are omitted. You can
//! annotate your error with then by enabling the `backtrace` feature.
//!
//! ```toml
//! [dependencies]
//! json_env_logger = { version = "0.1", features = ["backtrace"] }
//! ```

// export to make types accessible without
// requiring adding another Cargo.toml dependency
#[doc(hidden)]
pub extern crate env_logger;

use env_logger::Builder;
use log::kv;
use std::{
    io::{self, Write},
    panic, thread,
};

/// Register configured json env logger implementation with `log` crate.
///
/// Applications should ensure this fn gets called once and only once per application
/// lifetime
///
/// # panics
///
/// Panics of logger has already been configured
pub fn init() {
    try_init().unwrap()
}

/// Register configured json env logger with `log` crate
///
/// Will yield an `log::SetLoggerError` when a logger has already
/// been configured
pub fn try_init() -> Result<(), log::SetLoggerError> {
    builder().try_init()
}

/// Register a panic hook that serializes panic information as json
/// and logs via `log::error`
pub fn panic_hook() {
    panic::set_hook(Box::new(|info| {
        let thread = thread::current();
        let thread = thread.name().unwrap_or("unnamed");

        let msg = match info.payload().downcast_ref::<&'static str>() {
            Some(s) => *s,
            None => match info.payload().downcast_ref::<String>() {
                Some(s) => &**s,
                None => "Box<Any>",
            },
        };

        match info.location() {
            Some(location) => {
                #[cfg(not(feature = "backtrace"))]
                {
                    kv_log_macro::error!(
                        "panicked at '{}'", msg,
                        {
                            thread: thread,
                            location: format!("{}:{}", location.file(), location.line())
                        }
                    );
                }

                #[cfg(feature = "backtrace")]
                {
                    kv_log_macro::error!(
                        "panicked at '{}'", msg,
                        {
                            thread: thread,
                            location: format!("{}:{}", location.file(), location.line()),
                            backtrace: format!("{:?}", backtrace::Backtrace::new())
                        }
                    );
                }
            }
            None => {
                #[cfg(not(feature = "backtrace"))]
                {
                    kv_log_macro::error!("panicked at '{}'", msg, { thread: thread });
                }
                #[cfg(feature = "backtrace")]
                {
                    kv_log_macro::error!(
                        "panicked at '{}'", msg,
                        {
                            thread: thread,
                            backtrace: format!("{:?}", backtrace::Backtrace::new())
                        }
                    );
                }
            }
        }
    }));
}

/// Yields the standard `env_logger::Builder` configured to log in JSON format
pub fn builder() -> Builder {
    let mut builder = Builder::from_default_env();
    builder.format(write);
    builder
}

fn write<F>(
    f: &mut F,
    record: &log::Record,
) -> io::Result<()>
where
    F: Write,
{
    write!(f, "{{")?;
    write!(f, "\"level\":\"{}\",", record.level())?;

    #[cfg(feature = "iso-timestamps")]
    {
        write!(
            f,
            "\"ts\":\"{}\"",
            chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true)
        )?;
    }
    #[cfg(not(feature = "iso-timestamps"))]
    {
        write!(
            f,
            "\"ts\":{}",
            std::time::UNIX_EPOCH.elapsed().unwrap().as_millis()
        )?;
    }
    write!(f, ",\"msg\":")?;
    write_json_str(f, &record.args().to_string())?;

    struct Visitor<'a, W: Write> {
        writer: &'a mut W,
    }

    impl<'kvs, 'a, W: Write> kv::Visitor<'kvs> for Visitor<'a, W> {
        fn visit_pair(
            &mut self,
            key: kv::Key<'kvs>,
            val: kv::Value<'kvs>,
        ) -> Result<(), kv::Error> {
            write!(self.writer, ",\"{}\":{}", key, val).unwrap();
            Ok(())
        }
    }

    let mut visitor = Visitor { writer: f };
    record.key_values().visit(&mut visitor).unwrap();
    writeln!(f, "}}")
}

// until log kv Value impl serde::Serialize
fn write_json_str<W: io::Write>(
    writer: &mut W,
    raw: &str,
) -> std::io::Result<()> {
    serde_json::to_writer(writer, raw)?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::error::Error;

    #[test]
    fn writes_records_as_json() -> Result<(), Box<dyn Error>> {
        let record = log::Record::builder()
            .args(format_args!("hello"))
            .level(log::Level::Info)
            .build();
        let mut buf = Vec::new();
        write(&mut buf, &record)?;
        let output = std::str::from_utf8(&buf)?;
        assert!(serde_json::from_str::<serde_json::Value>(&output).is_ok());
        Ok(())
    }

    #[test]
    fn escapes_json_strings() -> Result<(), Box<dyn Error>> {
        let mut buf = Vec::new();
        write_json_str(
            &mut buf, r#""
	"#,
        )?;
        assert_eq!("\"\\\"\\n\\t\"", std::str::from_utf8(&buf)?);
        Ok(())
    }
}