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
use crate::exporter::DataDogExporter;
use crate::recorder::DataDogRecorder;
use crate::DataDogHandle;
use metrics::{Key, Label};
use metrics_util::{Handle, NotTracked, Registry};
use reqwest::Client;
use std::sync::Arc;

/// Builder for creating/installing a DataDog recorder/exporter
pub struct DataDogBuilder {
    write_to_stdout: bool,
    write_to_api: bool,
    api_host: String,
    api_key: Option<String>,
    tags: Vec<Label>,
}

impl DataDogBuilder {
    /// Creates a new [`DataDogBuilder`]
    pub fn default() -> Self {
        DataDogBuilder {
            write_to_stdout: true,
            write_to_api: false,
            api_host: "https://api.datadoghq.com/api/v1".to_string(),
            api_key: None,
            tags: vec![],
        }
    }

    /// Write metrics to stdout in DataDog JSON format
    pub fn write_to_stdout(self, b: bool) -> DataDogBuilder {
        DataDogBuilder {
            write_to_stdout: b,
            ..self
        }
    }

    /// Write metrics to DataDog API
    pub fn write_to_api(self, b: bool, api_key: Option<String>) -> DataDogBuilder {
        DataDogBuilder {
            write_to_api: b,
            api_key,
            ..self
        }
    }

    /// Set DataDog API host
    pub fn api_host(self, api_host: String) -> DataDogBuilder {
        DataDogBuilder { api_host, ..self }
    }

    /// Set tags to send with metrics
    pub fn tags(self, tags: Vec<(String, String)>) -> DataDogBuilder {
        DataDogBuilder {
            tags: tags.iter().map(Label::from).collect(),
            ..self
        }
    }

    /// Build [`DataDogHandle`]
    pub fn build(&self) -> DataDogHandle {
        let registry = Arc::new(Registry::<Key, Handle, NotTracked<Handle>>::untracked());
        let recorder = DataDogRecorder::new(registry.clone());
        let handle = DataDogExporter::new(
            registry,
            self.write_to_stdout,
            self.write_to_api,
            self.api_host.clone(),
            if self.write_to_api {
                Some(Client::default())
            } else {
                None
            },
            self.api_key.clone(),
            self.tags.clone(),
        );
        DataDogHandle { recorder, handle }
    }
}