logo
  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
//! Stdout Metrics Exporter
use crate::global;
use crate::sdk::{
    export::metrics::{
        CheckpointSet, Count, ExportKind, ExportKindFor, ExportKindSelector, Exporter, LastValue,
        Max, Min, Sum,
    },
    metrics::{
        aggregators::{
            ArrayAggregator, HistogramAggregator, LastValueAggregator, MinMaxSumCountAggregator,
            SumAggregator,
        },
        controllers::{self, PushController, PushControllerWorker},
        selectors::simple,
    },
};
use crate::{
    attributes::{default_encoder, AttributeSet, Encoder},
    metrics::{Descriptor, MetricsError, Result},
    KeyValue,
};
use futures_util::stream::Stream;
#[cfg(feature = "serialize")]
use serde::{Serialize, Serializer};
use std::fmt;
use std::io;
use std::iter;
use std::sync::Mutex;
use std::time::{Duration, SystemTime};

/// Create a new stdout exporter builder with the configuration for a stdout exporter.
pub fn stdout<S, SO, I, IS, ISI>(spawn: S, interval: I) -> StdoutExporterBuilder<io::Stdout, S, I>
where
    S: Fn(PushControllerWorker) -> SO,
    I: Fn(Duration) -> IS,
    IS: Stream<Item = ISI> + Send + 'static,
{
    StdoutExporterBuilder::<io::Stdout, S, I>::builder(spawn, interval)
}

///
#[derive(Debug)]
pub struct StdoutExporter<W> {
    /// Writer is the destination. If not set, `Stdout` is used.
    writer: Mutex<W>,
    /// Suppresses timestamp printing. This is useful to create deterministic test
    /// conditions.
    do_not_print_time: bool,
    /// Encodes the attributes.
    attribute_encoder: Box<dyn Encoder + Send + Sync>,
    /// An optional user-defined function to format a given export batch.
    formatter: Option<Formatter>,
}

/// A collection of exported lines
#[cfg_attr(feature = "serialize", derive(Serialize))]
#[derive(Default, Debug)]
pub struct ExportBatch {
    #[cfg_attr(feature = "serialize", serde(skip_serializing_if = "Option::is_none"))]
    timestamp: Option<SystemTime>,
    lines: Vec<ExportLine>,
}

#[cfg_attr(feature = "serialize", derive(Serialize))]
#[derive(Default, Debug)]
struct ExportLine {
    name: String,
    #[cfg_attr(feature = "serialize", serde(skip_serializing_if = "Option::is_none"))]
    min: Option<ExportNumeric>,
    #[cfg_attr(feature = "serialize", serde(skip_serializing_if = "Option::is_none"))]
    max: Option<ExportNumeric>,
    #[cfg_attr(feature = "serialize", serde(skip_serializing_if = "Option::is_none"))]
    sum: Option<ExportNumeric>,
    count: u64,
    #[cfg_attr(feature = "serialize", serde(skip_serializing_if = "Option::is_none"))]
    last_value: Option<ExportNumeric>,

    #[cfg_attr(feature = "serialize", serde(skip_serializing_if = "Option::is_none"))]
    timestamp: Option<SystemTime>,
}

/// A number exported as debug for serialization
pub struct ExportNumeric(Box<dyn fmt::Debug>);

impl fmt::Debug for ExportNumeric {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

#[cfg(feature = "serialize")]
impl Serialize for ExportNumeric {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let s = format!("{:?}", self);
        serializer.serialize_str(&s)
    }
}

impl<W> Exporter for StdoutExporter<W>
where
    W: fmt::Debug + io::Write,
{
    fn export(&self, checkpoint_set: &mut dyn CheckpointSet) -> Result<()> {
        let mut batch = ExportBatch::default();
        if !self.do_not_print_time {
            batch.timestamp = Some(crate::time::now());
        }
        checkpoint_set.try_for_each(self, &mut |record| {
            let agg = record.aggregator().ok_or(MetricsError::NoDataCollected)?;
            let desc = record.descriptor();
            let kind = desc.number_kind();
            let encoded_resource = record.resource().encoded(self.attribute_encoder.as_ref());
            let encoded_inst_attributes = if !desc.instrumentation_name().is_empty() {
                let inst_attributes = AttributeSet::from_attributes(iter::once(KeyValue::new(
                    "instrumentation.name",
                    desc.instrumentation_name().to_owned(),
                )));
                inst_attributes.encoded(Some(self.attribute_encoder.as_ref()))
            } else {
                String::new()
            };

            let mut expose = ExportLine::default();

            if let Some(array) = agg.as_any().downcast_ref::<ArrayAggregator>() {
                expose.count = array.count()?;
            }

            if let Some(last_value) = agg.as_any().downcast_ref::<LastValueAggregator>() {
                let (value, timestamp) = last_value.last_value()?;
                expose.last_value = Some(ExportNumeric(value.to_debug(kind)));

                if !self.do_not_print_time {
                    expose.timestamp = Some(timestamp);
                }
            }

            if let Some(histogram) = agg.as_any().downcast_ref::<HistogramAggregator>() {
                expose.sum = Some(ExportNumeric(histogram.sum()?.to_debug(kind)));
                expose.count = histogram.count()?;
                // TODO expose buckets
            }

            if let Some(mmsc) = agg.as_any().downcast_ref::<MinMaxSumCountAggregator>() {
                expose.min = Some(ExportNumeric(mmsc.min()?.to_debug(kind)));
                expose.max = Some(ExportNumeric(mmsc.max()?.to_debug(kind)));
                expose.sum = Some(ExportNumeric(mmsc.sum()?.to_debug(kind)));
                expose.count = mmsc.count()?;
            }

            if let Some(sum) = agg.as_any().downcast_ref::<SumAggregator>() {
                expose.sum = Some(ExportNumeric(sum.sum()?.to_debug(kind)));
            }

            let mut encoded_attributes = String::new();
            let iter = record.attributes().iter();
            if let (0, _) = iter.size_hint() {
                encoded_attributes = record
                    .attributes()
                    .encoded(Some(self.attribute_encoder.as_ref()));
            }

            let mut sb = String::new();

            sb.push_str(desc.name());

            if !encoded_attributes.is_empty()
                || !encoded_resource.is_empty()
                || !encoded_inst_attributes.is_empty()
            {
                sb.push('{');
                sb.push_str(&encoded_resource);
                if !encoded_inst_attributes.is_empty() && !encoded_resource.is_empty() {
                    sb.push(',');
                }
                sb.push_str(&encoded_inst_attributes);
                if !encoded_attributes.is_empty()
                    && (!encoded_inst_attributes.is_empty() || !encoded_resource.is_empty())
                {
                    sb.push(',');
                }
                sb.push_str(&encoded_attributes);
                sb.push('}');
            }

            expose.name = sb;

            batch.lines.push(expose);
            Ok(())
        })?;

        self.writer.lock().map_err(From::from).and_then(|mut w| {
            let formatted = match &self.formatter {
                Some(formatter) => formatter.0(batch)?,
                None => format!("{:?}\n", batch),
            };
            w.write_all(formatted.as_bytes())
                .map_err(|e| MetricsError::Other(e.to_string()))
        })
    }
}

impl<W> ExportKindFor for StdoutExporter<W>
where
    W: fmt::Debug + io::Write,
{
    fn export_kind_for(&self, descriptor: &Descriptor) -> ExportKind {
        ExportKindSelector::Stateless.export_kind_for(descriptor)
    }
}

/// A formatter for user-defined batch serialization.
pub struct Formatter(Box<dyn Fn(ExportBatch) -> Result<String> + Send + Sync>);
impl fmt::Debug for Formatter {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Formatter(closure)")
    }
}

/// Configuration for a given stdout exporter.
#[derive(Debug)]
pub struct StdoutExporterBuilder<W, S, I> {
    spawn: S,
    interval: I,
    writer: Mutex<W>,
    do_not_print_time: bool,
    quantiles: Option<Vec<f64>>,
    attribute_encoder: Option<Box<dyn Encoder + Send + Sync>>,
    period: Option<Duration>,
    formatter: Option<Formatter>,
}

impl<W, S, SO, I, IS, ISI> StdoutExporterBuilder<W, S, I>
where
    W: io::Write + fmt::Debug + Send + Sync + 'static,
    S: Fn(PushControllerWorker) -> SO,
    I: Fn(Duration) -> IS,
    IS: Stream<Item = ISI> + Send + 'static,
{
    fn builder(spawn: S, interval: I) -> StdoutExporterBuilder<io::Stdout, S, I> {
        StdoutExporterBuilder {
            spawn,
            interval,
            writer: Mutex::new(io::stdout()),
            do_not_print_time: false,
            quantiles: None,
            attribute_encoder: None,
            period: None,
            formatter: None,
        }
    }
    /// Set the writer that this exporter will use.
    pub fn with_writer<W2: io::Write>(self, writer: W2) -> StdoutExporterBuilder<W2, S, I> {
        StdoutExporterBuilder {
            spawn: self.spawn,
            interval: self.interval,
            writer: Mutex::new(writer),
            do_not_print_time: self.do_not_print_time,
            quantiles: self.quantiles,
            attribute_encoder: self.attribute_encoder,
            period: self.period,
            formatter: self.formatter,
        }
    }

    /// Hide the timestamps from exported results
    pub fn with_do_not_print_time(self, do_not_print_time: bool) -> Self {
        StdoutExporterBuilder {
            do_not_print_time,
            ..self
        }
    }

    /// Set the attribute encoder that this exporter will use.
    pub fn with_attribute_encoder<E>(self, attribute_encoder: E) -> Self
    where
        E: Encoder + Send + Sync + 'static,
    {
        StdoutExporterBuilder {
            attribute_encoder: Some(Box::new(attribute_encoder)),
            ..self
        }
    }

    /// Set the frequency in which metrics are exported.
    pub fn with_period(self, period: Duration) -> Self {
        StdoutExporterBuilder {
            period: Some(period),
            ..self
        }
    }

    /// Set a formatter for serializing export batch data
    pub fn with_formatter<T>(self, formatter: T) -> Self
    where
        T: Fn(ExportBatch) -> Result<String> + Send + Sync + 'static,
    {
        StdoutExporterBuilder {
            formatter: Some(Formatter(Box::new(formatter))),
            ..self
        }
    }

    /// Build a new push controller, returning errors if they arise.
    pub fn init(mut self) -> PushController {
        let period = self.period.take();
        let exporter = StdoutExporter {
            writer: self.writer,
            do_not_print_time: self.do_not_print_time,
            attribute_encoder: self.attribute_encoder.unwrap_or_else(default_encoder),
            formatter: self.formatter,
        };
        let mut push_builder = controllers::push(
            simple::Selector::Exact,
            ExportKindSelector::Stateless,
            exporter,
            self.spawn,
            self.interval,
        );
        if let Some(period) = period {
            push_builder = push_builder.with_period(period);
        }

        let controller = push_builder.build();
        global::set_meter_provider(controller.provider());
        controller
    }
}