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
//! Structured application logging.
//!
//! This module provides:
//!
//!  * The `emit!()` family of macros, for recording application events in an easily machine-readable format
//!  * Collectors for transmitting these events to back-end logging servers
//!
//! The emit macros are "structured" versions of the ones in the widely-used `log` crate. The `log` crate doesn't preserve the structure
//! of the events that are written through it. For example:
//!
//! ```ignore
//! info!("Hello, {}!", env::var("USERNAME").unwrap());
//! ```
//!
//! This writes `"Hello, nblumhardt!"` to the log as an block of text, which can't later be broken apart to reveal the username except
//! with regular expressions.
//!
//! The arguments passed to `emit` are named:
//!
//! ```ignore
//! info!("Hello, {}!", user: env::var("USERNAME").unwrap());
//! ```
//!
//! This event can be rendered into text identically to the `log` example, but structured data collectors also capture the
//! aguments as a key/value property pairs.
//!
//! ```js
//! {
//!   "@t": "2016-03-17T00:17:01.333Z",
//!   "@mt": "Hello, {user}!",
//!   "user": "nblumhardt",
//!   "target": "example_app"
//! }
//! ```
//!
//! Back-ends like Elasticsearch, Seq, and Splunk use these in queries such as `user == "nblumhardt"` without up-front log parsing.
//!
//! Arguments are captured using `serde`, so there's the potential for complex values to be logged so long as they're `serde::ser::Serialize`.
//!
//! Further, because the template (format) itself is captured, it can be hashed to compute an "event type" for precisely finding
//! all occurrences of the event regardless of the value of the `user` argument.
//!
//! # Examples
//!
//! The example below writes events to stdout.
//!
//! ```
//! #[macro_use]
//! extern crate emit;
//!
//! use std::env;
//! use emit::PipelineBuilder;
//! use emit::collectors::stdio::StdioCollector;
//! use emit::formatters::raw::RawFormatter;
//!
//! fn main() {
//!     let _flush = PipelineBuilder::new()
//!         .write_to(StdioCollector::new(RawFormatter::new()))
//!         .init();
//!
//!     info!("Hello, {}!", name: env::var("USERNAME").unwrap_or("User".to_string()));
//! }
//! ```
//!
//! Output:
//!
//! ```text
//! emit 2016-03-24T05:03:36Z Hello, {name}!
//!   name: "nblumhardt"
//!   target: "example_app"
//!
//! ```

extern crate chrono;

pub mod templates;
pub mod events;
pub mod pipeline;
pub mod collectors;
pub mod enrichers;
pub mod formatters;

#[cfg(test)]
mod test_support;

use std::fmt;

#[repr(usize)]
#[derive(Copy, Eq, Debug, PartialEq, Clone, Ord, PartialOrd)]
pub enum LogLevel {
    Error = 1, 
    Warn, 
    Info, 
    Debug, 
    Trace
}

impl AsRef<str> for LogLevel {
    fn as_ref(&self) -> &str {
        LOG_LEVEL_NAMES[*self as usize]
    }
}

#[repr(usize)]
#[derive(Copy, Eq, Debug, PartialEq, Clone, Ord, PartialOrd)]
pub enum LogLevelFilter {
    Off,
    Error, 
    Warn, 
    Info, 
    Debug, 
    Trace
}

static LOG_LEVEL_NAMES: [&'static str; 6] = ["OFF", "ERROR", "WARN", "INFO", "DEBUG", "TRACE"];

impl fmt::Display for LogLevel {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        write!(fmt, "{}", LOG_LEVEL_NAMES[*self as usize])
    }
}

impl LogLevelFilter {
    pub fn is_enabled(self, level: LogLevel) -> bool {
        self as usize >= level as usize
    }
}

/// Re-export `pipeline::builder::PipelineBuilder` so that clients don't need to
/// fully-qualify the hierarchy.
pub use pipeline::builder::PipelineBuilder;

#[macro_export]
#[doc(hidden)]
macro_rules! __emit_get_event_data {
    ($target:expr, $s:expr, $( $n:ident: $v:expr ),* ) => {{
        #[allow(unused_imports)]
        use std::fmt::Write;
        use std::collections;
        use $crate::events::IntoValue;

        // Underscores avoid the unused_mut warning
        let mut _names: Vec<&str> = vec![];
        let mut properties: collections::BTreeMap<&'static str, $crate::events::Value> = collections::BTreeMap::new();

        $(
            _names.push(stringify!($n));
            properties.insert(stringify!($n), $v.into_value());
        )*

        properties.insert("target", $target.into_value());

        let template = $crate::templates::MessageTemplate::from_format($s, &_names);

        (template, properties)
    }};
}

/// Emit an event to the ambient pipeline.
///
/// # Examples
///
/// The event below collects a `user` property and is emitted if the pipeline level includes
/// `LogLevel::Info`.
///
/// ```ignore
/// emit!(emit::LogLevel::Info, "Hello, {}!", user: env::var("USERNAME").unwrap());
/// ```
///
/// A `target` expression may be specified if required. When omitted the `target` property
/// will carry the current module name.
///
/// ```ignore
/// emit!(target: "greetings", emit::LogLevel::Info, "Hello, {}!", user: env::var("USERNAME").unwrap());
/// ```
#[macro_export]
macro_rules! emit {
    (target: $target:expr, $lvl:expr, $s:expr, $($n:ident: $v:expr),*) => {{
        let lvl = $lvl;
        if $crate::pipeline::ambient::is_enabled(lvl) {
            let (template, properties) = __emit_get_event_data!($target, $s, $($n: $v),*);
            let event = $crate::events::Event::new_now(lvl, template, properties);
            $crate::pipeline::ambient::emit(event);
        }
    }};

    ($lvl:expr, $s:expr, $($n:ident: $v:expr),*) => {{
        emit!(target: module_path!(), $lvl, $s, $($n: $v),*);
    }};
}

/// Emit an error event to the ambient pipeline.
///
/// # Examples
///
/// The example below will be emitted at the `emit::LogLevel::Error` level.
///
/// ```ignore
/// error!("Could not start {} on {}", cmd: "emitd", machine: "s123456");
/// ```
#[macro_export]
macro_rules! error {
    (target: $target:expr, $s:expr, $($n:ident: $v:expr),*) => {{
        emit!(target: $target, $crate::LogLevel::Error, $s, $($n: $v),*);
    }};

    ($s:expr, $($n:ident: $v:expr),*) => {{
        emit!($crate::LogLevel::Error, $s, $($n: $v),*);
    }};
}

/// Emit a warning event to the ambient pipeline.
///
/// # Examples
///
/// The example below will be emitted at the `emit::LogLevel::Warn` level.
///
/// ```ignore
/// warn!("SQL query took {} ms", elapsed: 7890);
/// ```
#[macro_export]
macro_rules! warn {
    (target: $target:expr, $s:expr, $($n:ident: $v:expr),*) => {{
        emit!(target: $target, $crate::LogLevel::Warn, $s, $($n: $v),*);
    }};

    ($s:expr, $($n:ident: $v:expr),*) => {{
        emit!($crate::LogLevel::Warn, $s, $($n: $v),*);
    }};
}

/// Emit an informational event to the ambient pipeline.
///
/// # Examples
///
/// The example below will be emitted at the `emit::LogLevel::Info` level.
///
/// ```ignore
/// info!("Hello, {}!", user: env::var("USERNAME").unwrap());
/// ```
#[macro_export]
macro_rules! info {
    (target: $target:expr, $s:expr, $($n:ident: $v:expr),*) => {{
        emit!(target: $target, $crate::LogLevel::Info, $s, $($n: $v),*);
    }};

    ($s:expr, $($n:ident: $v:expr),*) => {{
        emit!($crate::LogLevel::Info, $s, $($n: $v),*);
    }};
}

/// Emit a debugging event to the ambient pipeline.
///
/// # Examples
///
/// The example below will be emitted at the `emit::LogLevel::Debug` level.
///
/// ```ignore
/// debug!("Opening config file {}", filename: "dir/config.json");
/// ```
#[macro_export]
macro_rules! debug {
    (target: $target:expr, $s:expr, $($n:ident: $v:expr),*) => {{
        emit!(target: $target, $crate::LogLevel::Debug, $s, $($n: $v),*);
    }};

    ($s:expr, $($n:ident: $v:expr),*) => {{
        emit!($crate::LogLevel::Debug, $s, $($n: $v),*);
    }};
}

/// Emit a trace event to the ambient pipeline.
///
/// # Examples
///
/// The example below will be emitted at the `emit::LogLevel::Trace` level.
///
/// ```ignore
/// emdtrace!("{} called with arg {}", method: "start_frobbles()", count: 123);
/// ```
#[macro_export]
macro_rules! trace {
    (target: $target:expr, $s:expr, $($n:ident: $v:expr),*) => {{
        emit!(target: $target, $crate::LogLevel::Trace, $s, $($n: $v),*);
    }};

    ($s:expr, $($n:ident: $v:expr),*) => {{
        emit!($crate::LogLevel::Trace, $s, $($n: $v),*);
    }};
}

#[cfg(test)]
mod tests {
    use enrichers::fixed_property::FixedPropertyEnricher;
    use pipeline::builder::PipelineBuilder;
    use std::env;
    use LogLevelFilter;
    use events::IntoValue;
    use collectors::stdio::StdioCollector;
    use formatters::json::{JsonFormatter,RenderedJsonFormatter};
    use formatters::text::PlainTextFormatter;
    use formatters::raw::RawFormatter;

    #[test]
    fn unparameterized_templates_are_captured() {
        let (template, properties) = __emit_get_event_data!("t", "Starting...",);
        assert_eq!(template.text(), "Starting...");
        assert_eq!(properties.len(), 1);
    }

    #[test]
    fn template_and_properties_are_captured() {
        let u = "nblumhardt";
        let q = 42;

        let (template, properties) = __emit_get_event_data!("t", "User {} exceeded quota of {}!", user: u, quota: q);
        assert_eq!(template.text(), "User {user} exceeded quota of {quota}!");
        assert_eq!(properties.get("user"), Some(&"nblumhardt".into_value()));
        assert_eq!(properties.get("quota"), Some(&42.into_value()));
        assert_eq!(properties.len(), 3);
    }

    #[test]
    fn pipeline_example() {
        let _flush = PipelineBuilder::new()
            .at_level(LogLevelFilter::Info)
            .pipe(Box::new(FixedPropertyEnricher::new("app", "Test".into_value())))
            .write_to(StdioCollector::new(PlainTextFormatter::new()))
            .write_to(StdioCollector::new(JsonFormatter::new()))
            .write_to(StdioCollector::new(RenderedJsonFormatter::new()))
            .write_to(StdioCollector::new(RawFormatter::new()))
            .init();

        info!("Hello, {} at {} in {}!", name: env::var("USERNAME").unwrap_or("User".to_string()), time: 2139, room: "office");
    }
}