tracing_loki_fmt/
lib.rs

1use crate::layer::Layer;
2use crate::proto::logproto::EntryAdapter;
3use crate::task::SenderTask;
4use parking_lot::Mutex;
5use std::collections::HashMap;
6use std::sync::Arc;
7use tracing::Level;
8use tracing_subscriber::fmt;
9use url::Url;
10
11mod layer;
12mod task;
13
14pub mod proto {
15    include!(concat!(env!("OUT_DIR"), "/proto.rs"));
16}
17
18const CAPACITY: usize = 1024;
19
20struct EventWrapper {
21    entry: EntryAdapter,
22    level: Level,
23}
24
25pub struct Builder<S, N, E> {
26    url: Url,
27    fmt_layer: fmt::Layer<S, N, E>,
28    labels: HashMap<String, String>,
29    fields: HashMap<String, String>,
30}
31
32impl<S, N, E> Builder<S, N, E> {
33    pub fn new(
34        url: impl AsRef<str>,
35        fmt_layer: fmt::Layer<S, N, E>,
36    ) -> Result<Self, url::ParseError> {
37        Ok(Self {
38            url: Url::parse(url.as_ref())?,
39            fmt_layer,
40            labels: HashMap::new(),
41            fields: HashMap::new(),
42        })
43    }
44
45    pub fn add_label(mut self, key: impl AsRef<str>, value: impl AsRef<str>) -> Self {
46        self.add_label_mut(key, value);
47        self
48    }
49
50    pub fn add_label_mut(&mut self, key: impl AsRef<str>, value: impl AsRef<str>) -> &mut Self {
51        self.labels
52            .insert(key.as_ref().into(), value.as_ref().into());
53        self
54    }
55
56    pub fn add_field(mut self, key: impl AsRef<str>, value: impl AsRef<str>) -> Self {
57        self.add_field_mut(key, value);
58        self
59    }
60
61    pub fn add_field_mut(&mut self, key: impl AsRef<str>, value: impl AsRef<str>) -> &mut Self {
62        self.fields
63            .insert(key.as_ref().into(), value.as_ref().into());
64        self
65    }
66
67    pub fn build(self) -> (Layer<S, N, E>, SenderTask) {
68        let buf = Arc::new(Mutex::new(Default::default()));
69
70        (
71            Layer::new(buf.clone(), self.fmt_layer),
72            SenderTask::new(buf, self.url, self.labels, self.fields),
73        )
74    }
75}