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
//! Span log.
#[cfg(feature = "stacktrace")]
use backtrace::Backtrace;
use std::borrow::Cow;
use std::time::SystemTime;

/// Span log builder.
#[derive(Debug)]
pub struct LogBuilder {
    fields: Vec<LogField>,
    time: Option<SystemTime>,
}
impl LogBuilder {
    /// Adds the field.
    pub fn field<T: Into<LogField>>(&mut self, field: T) -> &mut Self {
        self.fields.push(field.into());
        self
    }

    /// Sets the value of timestamp to `time`.
    pub fn time(&mut self, time: SystemTime) -> &mut Self {
        self.time = Some(time);
        self
    }

    /// Returns a specialized builder for the standard log fields.
    pub fn std(&mut self) -> StdLogFieldsBuilder {
        StdLogFieldsBuilder(self)
    }

    /// Returns a specialized builder for the standard error log fields.
    pub fn error(&mut self) -> StdErrorLogFieldsBuilder {
        self.field(LogField::new("event", "error"));
        StdErrorLogFieldsBuilder(self)
    }

    pub(crate) fn new() -> Self {
        LogBuilder {
            fields: Vec::new(),
            time: None,
        }
    }

    pub(crate) fn finish(mut self) -> Option<Log> {
        if self.fields.is_empty() {
            None
        } else {
            self.fields.reverse();
            self.fields.sort_by(|a, b| a.name.cmp(&b.name));
            self.fields.dedup_by(|a, b| a.name == b.name);
            Some(Log {
                fields: self.fields,
                time: self.time.unwrap_or_else(SystemTime::now),
            })
        }
    }
}

/// Span log.
#[derive(Debug, Clone)]
pub struct Log {
    fields: Vec<LogField>,
    time: SystemTime,
}
impl Log {
    /// Returns the fields of this log.
    pub fn fields(&self) -> &[LogField] {
        &self.fields
    }

    /// Returns the timestamp of this log.
    pub fn time(&self) -> SystemTime {
        self.time
    }
}

/// Span log field.
#[derive(Debug, Clone)]
pub struct LogField {
    name: Cow<'static, str>,
    value: Cow<'static, str>,
}
impl LogField {
    /// Makes a new `LogField` instance.
    pub fn new<N, V>(name: N, value: V) -> Self
    where
        N: Into<Cow<'static, str>>,
        V: Into<Cow<'static, str>>,
    {
        LogField {
            name: name.into(),
            value: value.into(),
        }
    }

    /// Returns the name of this field.
    pub fn name(&self) -> &str {
        self.name.as_ref()
    }

    /// Returns the value of this field.
    pub fn value(&self) -> &str {
        self.value.as_ref()
    }
}
impl<N, V> From<(N, V)> for LogField
where
    N: Into<Cow<'static, str>>,
    V: Into<Cow<'static, str>>,
{
    fn from((n, v): (N, V)) -> Self {
        LogField::new(n, v)
    }
}

/// A specialized span log builder for [the standard log fields].
///
/// [the standard log fields]: https://github.com/opentracing/specification/blob/master/semantic_conventions.md#log-fields-table
#[derive(Debug)]
pub struct StdLogFieldsBuilder<'a>(&'a mut LogBuilder);
impl<'a> StdLogFieldsBuilder<'a> {
    /// Adds the field `LogField::new("event", event)`.
    ///
    /// `event` is a stable identifier for some notable moment in the lifetime of a Span.
    /// For instance, a mutex lock acquisition or release or the sorts of lifetime events
    /// in a browser page load described in the [Performance.timing] specification.
    ///
    /// E.g., from Zipkin, `"cs"`, `"sr"`, `"ss"`, or `"cr"`.
    /// Or, more generally, `"initialized"` or `"timed out"`.
    ///
    /// [Performance.timing]: https://developer.mozilla.org/en-US/docs/Web/API/PerformanceTiming
    pub fn event<T>(&mut self, event: T) -> &mut Self
    where
        T: Into<Cow<'static, str>>,
    {
        self.0.field(LogField::new("event", event));
        self
    }

    /// Adds the field `LogField::new("message", message)`.
    ///
    /// `message` is a concise, human-readable, one-line message explaining the event.
    ///
    /// E.g., `"Could not connect to backend"`, `"Cache invalidation succeeded"`
    pub fn message<T>(&mut self, message: T) -> &mut Self
    where
        T: Into<Cow<'static, str>>,
    {
        self.0.field(LogField::new("message", message));
        self
    }

    #[cfg(feature = "stacktrace")]
    /// Adds the field `LogField::new("stack", {stack trace})`.
    pub fn stack(&mut self) -> &mut Self {
        self.0
            .field(LogField::new("stack", format!("{:?}", Backtrace::new())));
        self
    }
}

/// A specialized span log builder for [the standard error log fields].
///
/// This builder automatically inserts the field `LogField::new("event", "error")`.
///
/// [the standard error log fields]: https://github.com/opentracing/specification/blob/master/semantic_conventions.md#log-fields-table
#[derive(Debug)]
pub struct StdErrorLogFieldsBuilder<'a>(&'a mut LogBuilder);
impl<'a> StdErrorLogFieldsBuilder<'a> {
    /// Adds the field `LogField::new("error.kind", kind)`.
    ///
    /// `kind` is the type or "kind" of an error.
    ///
    /// E.g., `"Exception"`, `"OSError"`
    pub fn kind<T>(&mut self, kind: T) -> &mut Self
    where
        T: Into<Cow<'static, str>>,
    {
        self.0.field(LogField::new("error.kind", kind));
        self
    }

    /// Adds the field `LogField::new("message", message)`.
    ///
    /// `message` is a concise, human-readable, one-line message explaining the event.
    ///
    /// E.g., `"Could not connect to backend"`, `"Cache invalidation succeeded"`
    pub fn message<T>(&mut self, message: T) -> &mut Self
    where
        T: Into<Cow<'static, str>>,
    {
        self.0.field(LogField::new("message", message));
        self
    }

    #[cfg(feature = "stacktrace")]
    /// Adds the field `LogField::new("stack", {stack trace})`.
    pub fn stack(&mut self) -> &mut Self {
        self.0
            .field(LogField::new("stack", format!("{:?}", Backtrace::new())));
        self
    }
}