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
use crate::attributes::{Attributes, Buffered, MetricId, OnFlush, Prefixed, WithAttributes};
use crate::input::{Input, InputKind, InputMetric, InputScope};
use crate::name::MetricName;
use crate::output::format::{Formatting, LineFormat, SimpleFormat};
use crate::Flush;
use crate::{CachedInput, QueuedInput};

use std::sync::Arc;

#[cfg(not(feature = "parking_lot"))]
use std::sync::RwLock;

#[cfg(feature = "parking_lot")]
use parking_lot::RwLock;

use std::io;
use std::io::Write;

/// Buffered metrics log output.
#[derive(Clone)]
pub struct Log {
    attributes: Attributes,
    format: Arc<dyn LineFormat>,
    level: log::Level,
    target: Option<String>,
}

impl Input for Log {
    type SCOPE = LogScope;

    fn metrics(&self) -> Self::SCOPE {
        LogScope {
            attributes: self.attributes.clone(),
            entries: Arc::new(RwLock::new(Vec::new())),
            log: self.clone(),
        }
    }
}

impl WithAttributes for Log {
    fn get_attributes(&self) -> &Attributes {
        &self.attributes
    }
    fn mut_attributes(&mut self) -> &mut Attributes {
        &mut self.attributes
    }
}

impl Buffered for Log {}

impl Formatting for Log {
    fn formatting(&self, format: impl LineFormat + 'static) -> Self {
        let mut cloned = self.clone();
        cloned.format = Arc::new(format);
        cloned
    }
}

/// A scope for metrics log output.
#[derive(Clone)]
pub struct LogScope {
    attributes: Attributes,
    entries: Arc<RwLock<Vec<Vec<u8>>>>,
    log: Log,
}

impl Log {
    /// Write metric values to the standard log using `info!`.
    // TODO parameterize log level, logger
    pub fn to_log() -> Log {
        Log {
            attributes: Attributes::default(),
            format: Arc::new(SimpleFormat::default()),
            level: log::Level::Info,
            target: None,
        }
    }

    /// Sets the log `target` to use when logging metrics.
    /// See the (log!)[https://docs.rs/log/0.4.6/log/macro.log.html] documentation.
    pub fn level(&self, level: log::Level) -> Self {
        let mut cloned = self.clone();
        cloned.level = level;
        cloned
    }

    /// Sets the log `target` to use when logging metrics.
    /// See the (log!)[https://docs.rs/log/0.4.6/log/macro.log.html] documentation.
    pub fn target(&self, target: &str) -> Self {
        let mut cloned = self.clone();
        cloned.target = Some(target.to_string());
        cloned
    }
}

impl WithAttributes for LogScope {
    fn get_attributes(&self) -> &Attributes {
        &self.attributes
    }
    fn mut_attributes(&mut self) -> &mut Attributes {
        &mut self.attributes
    }
}

impl Buffered for LogScope {}

impl QueuedInput for Log {}
impl CachedInput for Log {}

impl InputScope for LogScope {
    fn new_metric(&self, name: MetricName, kind: InputKind) -> InputMetric {
        let name = self.prefix_append(name);
        let template = self.log.format.template(&name, kind);
        let entries = self.entries.clone();

        if self.is_buffered() {
            // buffered
            InputMetric::new(MetricId::forge("log", name), move |value, labels| {
                let mut buffer = Vec::with_capacity(32);
                match template.print(&mut buffer, value, |key| labels.lookup(key)) {
                    Ok(()) => {
                        let mut entries = write_lock!(entries);
                        entries.push(buffer)
                    }
                    Err(err) => debug!("Could not format buffered log metric: {}", err),
                }
            })
        } else {
            // unbuffered
            let level = self.log.level;
            let target = self.log.target.clone();
            InputMetric::new(MetricId::forge("log", name), move |value, labels| {
                let mut buffer = Vec::with_capacity(32);
                match template.print(&mut buffer, value, |key| labels.lookup(key)) {
                    Ok(()) => {
                        if let Some(target) = &target {
                            log!(target: target, level, "{:?}", &buffer)
                        } else {
                            log!(level, "{:?}", &buffer)
                        }
                    }
                    Err(err) => debug!("Could not format buffered log metric: {}", err),
                }
            })
        }
    }
}

impl Flush for LogScope {
    fn flush(&self) -> io::Result<()> {
        self.notify_flush_listeners();
        let mut entries = write_lock!(self.entries);
        if !entries.is_empty() {
            let mut buf: Vec<u8> = Vec::with_capacity(32 * entries.len());
            for entry in entries.drain(..) {
                writeln!(&mut buf, "{:?}", &entry)?;
            }
            if let Some(target) = &self.log.target {
                log!(target: target, self.log.level, "{:?}", &buf)
            } else {
                log!(self.log.level, "{:?}", &buf)
            }
        }
        Ok(())
    }
}

impl Drop for LogScope {
    fn drop(&mut self) {
        if let Err(e) = self.flush() {
            warn!("Could not flush log metrics on Drop. {}", e)
        }
    }
}

#[cfg(test)]
mod test {
    use crate::input::*;

    #[test]
    fn test_to_log() {
        let c = super::Log::to_log().metrics();
        let m = c.new_metric("test".into(), InputKind::Marker);
        m.write(33, labels![]);
    }
}