1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub struct TraceContext {
32 pub trace_id: TraceId,
34 pub span_id: SpanId,
36 pub sampled: bool,
38}
39
40#[derive(Debug, Clone, Copy, Default)]
42pub struct Targets {
43 pub log: bool,
45 pub report: bool,
47 pub breadcrumb: bool,
49}
50
51impl Targets {
52 pub fn any(self) -> bool {
54 self.log || self.report || self.breadcrumb
55 }
56}
57
58#[derive(Debug, Clone, PartialEq, Eq)]
63pub struct LoggedError {
64 class: String,
68 message: String,
70 sources: Vec<(String, String)>,
73}
74
75impl LoggedError {
76 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 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 fn sources_json(&self) -> Value {
102 self.sources
103 .iter()
104 .map(|(class, message)| json!({ "class": class, "message": message }))
105 .collect()
106 }
107}
108
109fn logged_class(error: &(dyn Error + 'static)) -> String {
112 erased_exception_class(error).unwrap_or_else(|| FALLBACK_EXCEPTION_CLASS.to_owned())
113}
114
115#[derive(Debug, Clone, PartialEq)]
117#[non_exhaustive]
118pub struct LogLine {
119 pub target: Cow<'static, str>,
123 pub message: String,
125 pub severity: Severity,
127 pub fields: Vec<KeyValue>,
129 pub file: Option<String>,
131 pub line: Option<u32>,
133 pub trace: Option<TraceContext>,
135 pub entry_point: Option<EntryPoint>,
147 pub error: Option<LoggedError>,
151}
152
153impl LogLine {
154 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 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 pub fn level(&self) -> Level {
193 self.severity.into()
194 }
195
196 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 let target = mem::take(&mut self.target);
217 client.send_log(target, self.into_log_record());
218 }
219 }
220
221 #[cfg(test)]
224 fn to_log_record(&self) -> LogRecord {
225 self.clone().into_log_record()
226 }
227
228 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 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 pub(crate) fn to_report(&self, app_crates: &[String]) -> Report {
285 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 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 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 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 #[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}