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
//! JSON Logger
//!
//! This logger follows the [Bunyan](https://github.com/trentm/node-bunyan) logging format.
//!
//! ### Example
//!
//! ```rust,ignore
//! #[macro_use] extern crate log;
//! extern crate json_logger;
//! extern crate rustc_serialize;
//!
//! use log::LogLevelFilter;
//! use rustc_serialize::json;
//!
//! #[derive(RustcEncodable)]
//! struct LogMessage<'a> {
//!     msg: &'a str,
//!     event: &'a str
//! }
//!
//! fn main() {
//!     json_logger::init("app_name", LogLevelFilter::Info).unwrap();
//!
//!     // This string will show up in the "msg" property
//!     info!("sample message");
//!
//!     // This will extend the log message JSON with additional properties
//!     info!("{}", json::encode(&LogMessage {
//!         msg: "sample message 2", event: "structured log"
//!     }).unwrap());
//! }
//! ```

extern crate libc;
extern crate log;
extern crate rustc_serialize;
extern crate time;

use std::default::Default;
use std::io::prelude::*;
use std::io::{self, Stdout};
use std::borrow::ToOwned;
use std::str;
use libc::{c_char, c_int, size_t, getpid};
use log::{LogRecord, Log, LogLevel, LogLevelFilter, LogMetadata, SetLoggerError};
use rustc_serialize::json::{self, ToJson, Json, Object};

extern {
    fn gethostname(name: *mut c_char, len: size_t) -> c_int;
}

pub struct JsonLogger {
    out: Stdout,
    level: LogLevelFilter,
    name: String,
    hostname: String,
    pid: i32
}

impl Log for JsonLogger {
    fn enabled(&self, metadata: &LogMetadata) -> bool {
        metadata.level() <= self.level
    }

    fn log(&self, record: &LogRecord) {
        let location = record.location();

        let mut root = Object::new();
        root.insert("hostname".to_owned(), self.hostname.to_json());
        root.insert("level".to_owned(), match record.level() {
            LogLevel::Error => Json::U64(50),
            LogLevel::Warn => Json::U64(40),
            LogLevel::Info => Json::U64(30),
            LogLevel::Debug => Json::U64(20),
            LogLevel::Trace => Json::U64(10)
        });
        root.insert("name".to_owned(), self.name.to_json());
        root.insert("pid".to_owned(), self.pid.to_json());
        root.insert("msg".to_owned(), Json::Null);

        let mut src = Object::new();
        src.insert("module_path".to_owned(), location.module_path().to_json());
        src.insert("file".to_owned(), location.file().to_json());
        src.insert("line".to_owned(), location.line().to_json());

        root.insert("src".to_owned(), Json::Object(src));
        root.insert("time".to_owned(), Json::String(time::now_utc().rfc3339().to_string()));
        root.insert("v".to_owned(), Json::U64(0));

        let s = record.args().to_string();
        match Json::from_str(&s).ok() {
            Some(j) => {
                if let Json::Object(obj) = j {
                    root.extend(obj);
                }
            },
            None => {
                // If the log message is not JSON,

                // we will fallback to treating it as a normal string.

                root.insert("msg".to_owned(), Json::String(s));
            }
        }

        if let Ok(s) = json::encode(&root) {
            let _ = writeln!(&mut self.out.lock(), "{}", s);
        }
    }
}

pub fn init(name: &str, level: LogLevelFilter) -> Result<(), SetLoggerError> {
    let mut buf = vec![0; 255];
    let err = unsafe {
        gethostname(buf.as_mut_ptr() as *mut c_char, buf.len() as size_t)
    };
    let hostname = if err == 0 {
        let len = buf.iter().position(|byte| *byte == 0).unwrap_or(buf.len());
        str::from_utf8(&buf[..len]).ok().unwrap_or_default().to_string()
    } else {
        String::default()
    };

    let pid = unsafe { getpid() };

    let logger = JsonLogger {
        out: io::stdout(),
        level: level,
        name: name.to_owned(),
        hostname: hostname,
        pid: pid
    };

    log::set_logger(|max_log_level| {
        max_log_level.set(level);
        Box::new(logger)
    })
}