Skip to main content

flareapp_core/
log_line.rs

1//! One log line from a logging integration, and what the Flare client makes of
2//! it: an OTLP log record, a breadcrumb, or an error report.
3//!
4//! The `tracing` and `log` integrations both turn their log lines into a
5//! [`LogLine`], so the conversion lives in one place.
6
7use std::borrow::Cow;
8use std::collections::BTreeMap;
9use std::error::Error;
10use std::iter;
11use std::mem;
12use std::panic::Location;
13use std::path::Path;
14use std::thread;
15
16use serde_json::{Value, json};
17
18use flareapp_otlp::{KeyValue, LogRecord, Severity, SpanId, TraceId};
19
20use crate::client::Client;
21use crate::entry_point::{EntryPoint, resolve_entry_point};
22use crate::level::Level;
23use crate::report::{
24    FALLBACK_EXCEPTION_CLASS, Frame, Report, erased_exception_class, fields_to_json,
25};
26use crate::scope::{add_log_breadcrumb, has_nested_entry_point};
27use crate::source_path::is_application_file;
28
29/// The trace and span a log line belongs to.
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub struct TraceContext {
32    /// The trace the line happened in.
33    pub trace_id: TraceId,
34    /// The span the line happened in.
35    pub span_id: SpanId,
36    /// Whether the trace is sampled.
37    pub sampled: bool,
38}
39
40/// Where [`LogLine::send`] delivers a line.
41#[derive(Debug, Clone, Copy, Default)]
42pub struct Targets {
43    /// Send the line to Flare as an OTLP log record.
44    pub log: bool,
45    /// Send the line as an error report.
46    pub report: bool,
47    /// Keep the line as a breadcrumb in the current scope.
48    pub breadcrumb: bool,
49}
50
51impl Targets {
52    /// Returns `true` when at least one target is on.
53    pub fn any(self) -> bool {
54        self.log || self.report || self.breadcrumb
55    }
56}
57
58/// An error that a log line carries, like the `error` field of a `tracing` event.
59///
60/// A logging integration only borrows the error while it reads the line, so the
61/// line keeps a copy of what an error report needs.
62#[derive(Debug, Clone, PartialEq, Eq)]
63pub struct LoggedError {
64    /// The exception class. A `&dyn Error` has no type name, so this is the name
65    /// that [`erased_exception_class`] reads from the `Debug` output, like
66    /// `RowNotFound` or `reqwest::Error`.
67    class: String,
68    /// The `Display` output of the error.
69    message: String,
70    /// The class and message of each error in the [`Error::source`] chain, the
71    /// direct cause first.
72    sources: Vec<(String, String)>,
73}
74
75impl LoggedError {
76    /// Copies the class, the message and the causes of `error`.
77    pub fn new(error: &(dyn Error + 'static)) -> Self {
78        let sources = iter::successors(error.source(), |&source| source.source())
79            .map(|source| (logged_class(source), source.to_string()))
80            .collect();
81
82        Self {
83            class: logged_class(error),
84            message: error.to_string(),
85            sources,
86        }
87    }
88
89    /// Returns a report of the error: its class and its message, and its causes
90    /// in the `error` context. The location of the report is a placeholder.
91    fn to_report(&self) -> Report {
92        let mut report = Report::new(self.class.clone(), self.message.clone(), Location::caller());
93        if !self.sources.is_empty() {
94            report.set_context("error", json!({ "sources": self.sources_json() }));
95        }
96
97        report
98    }
99
100    /// Returns the causes as JSON, for the context of a report.
101    fn sources_json(&self) -> Value {
102        self.sources
103            .iter()
104            .map(|(class, message)| json!({ "class": class, "message": message }))
105            .collect()
106    }
107}
108
109/// Returns the exception class of an error behind a `&dyn Error`, or a fallback
110/// when its `Debug` output has no name.
111fn logged_class(error: &(dyn Error + 'static)) -> String {
112    erased_exception_class(error).unwrap_or_else(|| FALLBACK_EXCEPTION_CLASS.to_owned())
113}
114
115/// A log line, in the shape every logging integration can produce.
116#[derive(Debug, Clone, PartialEq)]
117#[non_exhaustive]
118pub struct LogLine {
119    /// The `tracing` or `log` target that wrote the line, like `my_app::billing`.
120    /// It is the module path, unless the code sets another target. Flare shows it
121    /// as the target of the log.
122    pub target: Cow<'static, str>,
123    /// The message, like `order placed`.
124    pub message: String,
125    /// The severity. Flare's [`Level`] is derived from it.
126    pub severity: Severity,
127    /// The structured fields of the line, like `order_id = 7`.
128    pub fields: Vec<KeyValue>,
129    /// The source file that wrote the line, when known.
130    pub file: Option<String>,
131    /// The line number in the source file, when known.
132    pub line: Option<u32>,
133    /// The trace and span the line happened in, when there is one.
134    pub trace: Option<TraceContext>,
135    /// The entry point of the closest `tracing` span around the line that has an
136    /// entry point, like the `server` span of a request. `None` means that no
137    /// span around the line has one.
138    ///
139    /// Integrations must set this field when they send the line as a log record
140    /// or as a report. The log record and the report do not search the spans
141    /// again, because the current span can differ from the span of the line, for
142    /// example for an event with `parent: None`. An integration can leave this
143    /// field `None` when a nested scope has an entry point, because that entry
144    /// point wins over every span. [`LogLine::search_entry_point`] sets this field
145    /// and skips the search in that case.
146    pub entry_point: Option<EntryPoint>,
147    /// The error the line logs, like the `error` field of a `tracing` event. When
148    /// the line is sent as an error report, the report shows this error instead of
149    /// the message.
150    pub error: Option<LoggedError>,
151}
152
153impl LogLine {
154    /// Creates a line with a target, a message and a severity. The other fields
155    /// start empty, and integrations set them afterwards. For a log record or a
156    /// report, integrations must also set [`LogLine::entry_point`].
157    pub fn new<T, M>(target: T, message: M, severity: Severity) -> Self
158    where
159        T: Into<Cow<'static, str>>,
160        M: Into<String>,
161    {
162        Self {
163            target: target.into(),
164            message: message.into(),
165            severity,
166            fields: Vec::new(),
167            file: None,
168            line: None,
169            trace: None,
170            entry_point: None,
171            error: None,
172        }
173    }
174
175    /// Sets [`LogLine::entry_point`] to the result of `search_spans`, which finds
176    /// the entry point of the closest `tracing` span around the line. This function
177    /// does not call `search_spans` when a nested scope has an entry point,
178    /// because that entry point wins over every span.
179    ///
180    /// Integrations call this function on the thread that made the line, for a
181    /// line that they send as a log record or as a report.
182    pub fn search_entry_point<F>(&mut self, search_spans: F)
183    where
184        F: FnOnce() -> Option<EntryPoint>,
185    {
186        if !has_nested_entry_point() {
187            self.entry_point = search_spans();
188        }
189    }
190
191    /// Returns the level of the line, as a Flare [`Level`].
192    pub fn level(&self) -> Level {
193        self.severity.into()
194    }
195
196    /// Delivers the line to the given `targets`.
197    ///
198    /// This function sends the report before it records the breadcrumb. That way,
199    /// the timeline of the report shows what happened before this line, and not
200    /// this line itself. The log record comes last, because it takes the message
201    /// and the fields of the line instead of a copy.
202    pub fn send(mut self, client: &Client, targets: Targets) {
203        if targets.report {
204            client.send_report(self.to_report(client.app_crates()));
205        }
206        if targets.breadcrumb {
207            let (message, fields) = if targets.log {
208                (self.message.clone(), self.fields.clone())
209            } else {
210                (mem::take(&mut self.message), mem::take(&mut self.fields))
211            };
212            add_log_breadcrumb(message, self.level(), fields);
213        }
214        if targets.log {
215            // Only the log record needs the target, so it can move out of the line.
216            let target = mem::take(&mut self.target);
217            client.send_log(target, self.into_log_record());
218        }
219    }
220
221    /// Turns a copy of the line into an OTLP log record. Only the tests call this
222    /// function. [`LogLine::send`] moves the line into the record instead.
223    #[cfg(test)]
224    fn to_log_record(&self) -> LogRecord {
225        self.clone().into_log_record()
226    }
227
228    /// Turns the line into an OTLP log record, with the trace context, the source
229    /// location, the thread name and the entry point of the work. This function
230    /// moves the message, the fields, the file and the entry point into the record
231    /// instead of copying them.
232    fn into_log_record(self) -> LogRecord {
233        let mut record = LogRecord::new(self.severity, self.message);
234        record.attributes = self.fields;
235
236        if let Some(trace) = self.trace {
237            record.trace_id = Some(trace.trace_id);
238            record.span_id = Some(trace.span_id);
239            record.flags = u32::from(trace.sampled);
240        }
241
242        if let Some(file) = self.file {
243            record
244                .attributes
245                .push(KeyValue::new("code.file.path", file));
246        }
247        if let Some(line) = self.line {
248            record
249                .attributes
250                .push(KeyValue::new("code.line.number", i64::from(line)));
251        }
252        if let Some(name) = thread::current().name() {
253            record
254                .attributes
255                .push(KeyValue::new("thread.name", name.to_owned()));
256        }
257        // Flare lists a log under the handler of its entry point, like the route
258        // `GET /users/{id}`.
259        record.attributes.extend(
260            resolve_entry_point(|| self.entry_point)
261                .into_attributes()
262                .into_iter()
263                .map(|(key, value)| KeyValue::new(key, value)),
264        );
265
266        record
267    }
268
269    /// Turns the line into an error report. The fields go into the report's context
270    /// under `log`, and the source location becomes its only frame.
271    ///
272    /// A line with an [`error`](LogLine::error) reports that error: its class and
273    /// message. The message of the line goes into the `log` context, unless the
274    /// message is empty or the same as the message of the error. The causes of the
275    /// error go into the `error` context. Flare drops causes without frames, and
276    /// Rust causes have none. A line without an error is reported like
277    /// [`Report::from_message`].
278    ///
279    /// The report does not search the spans for an entry point. It uses
280    /// [`LogLine::entry_point`].
281    ///
282    /// `app_crates` are the dependencies that count as application code. Pass
283    /// [`Client::app_crates`].
284    pub(crate) fn to_report(&self, app_crates: &[String]) -> Report {
285        // `Location::caller()` is only a placeholder. `set_location` replaces it
286        // with the place that wrote the line.
287        let mut report = match &self.error {
288            Some(error) => error.to_report(),
289            None => Report::from_message(self.message.clone(), self.level(), Location::caller()),
290        };
291        report.set_location(self.location_frame(app_crates));
292
293        let context = self.report_context();
294        if !context.is_empty() {
295            report.set_context("log", Value::Object(context.into_iter().collect()));
296        }
297        report.entry_point = Some(resolve_entry_point(|| self.entry_point.clone()));
298
299        report
300    }
301
302    /// Returns the place that wrote the line, as the frame of a report. Flare
303    /// needs at least one frame, also when the source file is unknown.
304    fn location_frame(&self, app_crates: &[String]) -> Frame {
305        Frame {
306            file: self.file.clone().unwrap_or_else(|| "<unknown>".to_owned()),
307            line_number: self.line.unwrap_or(0),
308            column_number: None,
309            method: None,
310            class: None,
311            is_application_frame: self
312                .file
313                .as_deref()
314                .is_some_and(|file| is_application_file(Path::new(file), app_crates)),
315            instruction_addr: None,
316        }
317    }
318
319    /// Returns the `log` context of a report: the fields of the line. When the
320    /// report shows the error of the line, the context also gets the message of
321    /// the line, unless it is empty or the same as the message of the error.
322    fn report_context(&self) -> BTreeMap<String, Value> {
323        let mut context = fields_to_json(&self.fields);
324        if let Some(error) = &self.error
325            && !self.message.is_empty()
326            && self.message != error.message
327        {
328            context.insert("message".to_owned(), Value::from(self.message.clone()));
329        }
330
331        context
332    }
333}
334
335#[cfg(test)]
336mod tests {
337    use std::fmt;
338
339    use flareapp_otlp::{AnyValue, Resource};
340
341    use super::*;
342    use crate::scope::with_scope;
343    use crate::test_support::{attribute, in_queue_span, serial};
344
345    fn line() -> LogLine {
346        let mut line = LogLine::new("shop::checkout", "payment declined", Severity::Warn);
347        line.fields = vec![KeyValue::new("order_id", 7_i64)];
348        line.file = Some("src/checkout.rs".to_owned());
349        line.line = Some(42);
350
351        line
352    }
353
354    /// Turns the line into an error report, and returns the JSON that Flare gets.
355    fn report_json(line: &LogLine) -> Value {
356        let mut report = line.to_report(&[]);
357        report.resolve_entry_point();
358        let resource = Resource::new(Vec::new());
359
360        let body = report.resolve_frames(false).encode(&resource).unwrap();
361
362        serde_json::from_slice(&body).unwrap()
363    }
364
365    #[test]
366    fn log_records_have_the_message_and_severity() {
367        let record = line().to_log_record();
368
369        assert_eq!(record.severity_number, Severity::Warn);
370        assert_eq!(record.body, "payment declined");
371    }
372
373    #[test]
374    fn log_records_have_the_fields() {
375        let record = line().to_log_record();
376
377        assert_eq!(
378            attribute(&record.attributes, "order_id"),
379            Some(&AnyValue::Int(7))
380        );
381    }
382
383    #[test]
384    fn log_records_have_the_source_location() {
385        let record = line().to_log_record();
386
387        assert_eq!(
388            attribute(&record.attributes, "code.file.path"),
389            Some(&AnyValue::String("src/checkout.rs".to_owned()))
390        );
391        assert_eq!(
392            attribute(&record.attributes, "code.line.number"),
393            Some(&AnyValue::Int(42))
394        );
395    }
396
397    #[test]
398    fn log_records_have_the_trace_context() {
399        let mut line = line();
400        line.trace = Some(TraceContext {
401            trace_id: TraceId::random(),
402            span_id: SpanId::random(),
403            sampled: true,
404        });
405
406        let record = line.to_log_record();
407
408        assert_eq!(record.trace_id, line.trace.map(|trace| trace.trace_id));
409        assert_eq!(record.span_id, line.trace.map(|trace| trace.span_id));
410        assert_eq!(record.flags, 1);
411    }
412
413    fn log_record_in_a_web_scope() -> LogRecord {
414        let entry_point =
415            EntryPoint::web("https://shop.test/users/7").handler_identifier("GET /users/{id}");
416
417        with_scope(
418            |scope| scope.set_entry_point(entry_point),
419            || line().to_log_record(),
420        )
421    }
422
423    #[test]
424    fn log_records_have_the_entry_point_type_of_the_scope() {
425        let record = log_record_in_a_web_scope();
426
427        assert_eq!(
428            attribute(&record.attributes, "flare.entry_point.type"),
429            Some(&AnyValue::String("web".to_owned()))
430        );
431    }
432
433    #[test]
434    fn log_records_have_the_handler_identifier_of_the_scope() {
435        let record = log_record_in_a_web_scope();
436
437        assert_eq!(
438            attribute(&record.attributes, "flare.entry_point.handler.identifier"),
439            Some(&AnyValue::String("GET /users/{id}".to_owned()))
440        );
441    }
442
443    #[test]
444    fn log_records_have_the_entry_point_of_their_span() {
445        let mut line = line();
446        line.entry_point = Some(EntryPoint::queue("send-invoice"));
447
448        let record = line.to_log_record();
449
450        assert_eq!(
451            attribute(&record.attributes, "flare.entry_point.type"),
452            Some(&AnyValue::String("queue".to_owned()))
453        );
454    }
455
456    #[test]
457    fn log_records_outside_any_work_are_commands() {
458        let _serial = serial();
459        let record = line().to_log_record();
460
461        assert_eq!(
462            attribute(&record.attributes, "flare.entry_point.type"),
463            Some(&AnyValue::String("cli".to_owned()))
464        );
465    }
466
467    #[test]
468    fn log_records_outside_any_work_are_rust_binaries() {
469        let _serial = serial();
470        let record = line().to_log_record();
471
472        assert_eq!(
473            attribute(&record.attributes, "flare.entry_point.handler.type"),
474            Some(&AnyValue::String("rust_binary".to_owned()))
475        );
476    }
477
478    #[test]
479    fn reports_from_log_lines_get_the_entry_point_of_their_span() {
480        let mut line = line();
481        line.entry_point = Some(EntryPoint::queue("send-invoice"));
482
483        let json = report_json(&line);
484
485        assert_eq!(json["attributes"]["flare.entry_point.type"], "queue");
486    }
487
488    #[test]
489    fn reports_from_log_lines_without_a_span_entry_point_ignore_the_current_span() {
490        let _serial = serial();
491
492        let json = in_queue_span(|| report_json(&line()));
493
494        assert_eq!(json["attributes"]["flare.entry_point.type"], "cli");
495    }
496
497    #[test]
498    fn reports_that_never_looked_for_a_span_use_the_current_span() {
499        let _serial = serial();
500
501        let entry_point = in_queue_span(|| {
502            let mut report = Report::from_message("x".to_owned(), Level::Error, Location::caller());
503            report.resolve_entry_point();
504
505            report.entry_point
506        });
507
508        assert_eq!(entry_point, Some(EntryPoint::queue("send-invoice")));
509    }
510
511    #[test]
512    fn reports_have_the_message_and_level() {
513        let json = report_json(&line());
514
515        assert_eq!(json["exceptionClass"], "Log");
516        assert_eq!(json["message"], "payment declined");
517        assert_eq!(json["level"], "warning");
518    }
519
520    #[test]
521    fn reports_use_the_log_location_as_their_frame() {
522        let json = report_json(&line());
523
524        assert_eq!(json["stacktrace"][0]["file"], "src/checkout.rs");
525        assert_eq!(json["stacktrace"][0]["lineNumber"], 42);
526    }
527
528    #[test]
529    fn reports_have_the_fields_as_context() {
530        let json = report_json(&line());
531
532        assert_eq!(
533            json["attributes"]["context.custom"]["log"],
534            json!({ "order_id": 7 })
535        );
536    }
537
538    #[derive(Debug)]
539    struct ForeignKeyViolation;
540
541    impl fmt::Display for ForeignKeyViolation {
542        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
543            f.write_str("insert violates foreign key constraint")
544        }
545    }
546
547    impl Error for ForeignKeyViolation {}
548
549    #[derive(Debug)]
550    enum QueryFailed {
551        Database(ForeignKeyViolation),
552    }
553
554    impl fmt::Display for QueryFailed {
555        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
556            f.write_str("error returned from database")
557        }
558    }
559
560    impl Error for QueryFailed {
561        fn source(&self) -> Option<&(dyn Error + 'static)> {
562            let Self::Database(violation) = self;
563
564            Some(violation)
565        }
566    }
567
568    fn line_with_error() -> LogLine {
569        let mut line = line();
570        line.error = Some(LoggedError::new(&QueryFailed::Database(
571            ForeignKeyViolation,
572        )));
573
574        line
575    }
576
577    #[test]
578    fn reports_of_lines_with_an_error_report_the_error() {
579        let json = report_json(&line_with_error());
580
581        assert_eq!(
582            (&json["exceptionClass"], &json["message"], &json["level"]),
583            (
584                &json!("Database"),
585                &json!("error returned from database"),
586                &Value::Null
587            )
588        );
589    }
590
591    #[test]
592    fn reports_of_lines_with_an_error_keep_the_message_as_context() {
593        let json = report_json(&line_with_error());
594
595        assert_eq!(
596            json["attributes"]["context.custom"]["log"],
597            json!({ "message": "payment declined", "order_id": 7 })
598        );
599    }
600
601    #[test]
602    fn reports_of_lines_with_an_error_list_its_causes_as_context() {
603        let json = report_json(&line_with_error());
604
605        assert_eq!(
606            json["attributes"]["context.custom"]["error"],
607            json!({ "sources": [{
608                "class": "ForeignKeyViolation",
609                "message": "insert violates foreign key constraint",
610            }] })
611        );
612    }
613
614    #[test]
615    fn reports_of_lines_with_an_error_without_causes_have_no_error_context() {
616        let mut line = line();
617        line.error = Some(LoggedError::new(&ForeignKeyViolation));
618
619        let json = report_json(&line);
620
621        assert_eq!(json["attributes"]["context.custom"]["error"], Value::Null);
622    }
623
624    /// Like the panic message that `tracing-panic` logs from its own file.
625    #[test]
626    fn reports_of_lines_from_a_dependency_have_no_application_frame() {
627        let mut line = line();
628        line.file = Some(
629            "/home/me/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/tracing-panic-0.1.2/src/lib.rs"
630                .to_owned(),
631        );
632
633        let json = report_json(&line);
634
635        assert_eq!(json["stacktrace"][0]["isApplicationFrame"], false);
636    }
637
638    #[test]
639    fn reports_of_lines_from_the_app_have_an_application_frame() {
640        let json = report_json(&line());
641
642        assert_eq!(json["stacktrace"][0]["isApplicationFrame"], true);
643    }
644
645    #[test]
646    fn reports_without_a_file_have_no_application_frame() {
647        let mut line = line();
648        line.file = None;
649
650        let json = report_json(&line);
651
652        assert_eq!(json["stacktrace"][0]["isApplicationFrame"], false);
653    }
654}