use std::borrow::Cow;
use std::collections::BTreeMap;
use std::error::Error;
use std::iter;
use std::mem;
use std::panic::Location;
use std::path::Path;
use std::thread;
use serde_json::{Value, json};
use flareapp_otlp::{KeyValue, LogRecord, Severity, SpanId, TraceId};
use crate::client::Client;
use crate::entry_point::{EntryPoint, resolve_entry_point};
use crate::level::Level;
use crate::report::{
FALLBACK_EXCEPTION_CLASS, Frame, Report, erased_exception_class, fields_to_json,
};
use crate::scope::{add_log_breadcrumb, has_nested_entry_point};
use crate::source_path::is_application_file;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TraceContext {
pub trace_id: TraceId,
pub span_id: SpanId,
pub sampled: bool,
}
#[derive(Debug, Clone, Copy, Default)]
pub struct Targets {
pub log: bool,
pub report: bool,
pub breadcrumb: bool,
}
impl Targets {
pub fn any(self) -> bool {
self.log || self.report || self.breadcrumb
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LoggedError {
class: String,
message: String,
sources: Vec<(String, String)>,
}
impl LoggedError {
pub fn new(error: &(dyn Error + 'static)) -> Self {
let sources = iter::successors(error.source(), |&source| source.source())
.map(|source| (logged_class(source), source.to_string()))
.collect();
Self {
class: logged_class(error),
message: error.to_string(),
sources,
}
}
fn to_report(&self) -> Report {
let mut report = Report::new(self.class.clone(), self.message.clone(), Location::caller());
if !self.sources.is_empty() {
report.set_context("error", json!({ "sources": self.sources_json() }));
}
report
}
fn sources_json(&self) -> Value {
self.sources
.iter()
.map(|(class, message)| json!({ "class": class, "message": message }))
.collect()
}
}
fn logged_class(error: &(dyn Error + 'static)) -> String {
erased_exception_class(error).unwrap_or_else(|| FALLBACK_EXCEPTION_CLASS.to_owned())
}
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct LogLine {
pub target: Cow<'static, str>,
pub message: String,
pub severity: Severity,
pub fields: Vec<KeyValue>,
pub file: Option<String>,
pub line: Option<u32>,
pub trace: Option<TraceContext>,
pub entry_point: Option<EntryPoint>,
pub error: Option<LoggedError>,
}
impl LogLine {
pub fn new<T, M>(target: T, message: M, severity: Severity) -> Self
where
T: Into<Cow<'static, str>>,
M: Into<String>,
{
Self {
target: target.into(),
message: message.into(),
severity,
fields: Vec::new(),
file: None,
line: None,
trace: None,
entry_point: None,
error: None,
}
}
pub fn search_entry_point<F>(&mut self, search_spans: F)
where
F: FnOnce() -> Option<EntryPoint>,
{
if !has_nested_entry_point() {
self.entry_point = search_spans();
}
}
pub fn level(&self) -> Level {
self.severity.into()
}
pub fn send(mut self, client: &Client, targets: Targets) {
if targets.report {
client.send_report(self.to_report(client.app_crates()));
}
if targets.breadcrumb {
let (message, fields) = if targets.log {
(self.message.clone(), self.fields.clone())
} else {
(mem::take(&mut self.message), mem::take(&mut self.fields))
};
add_log_breadcrumb(message, self.level(), fields);
}
if targets.log {
let target = mem::take(&mut self.target);
client.send_log(target, self.into_log_record());
}
}
#[cfg(test)]
fn to_log_record(&self) -> LogRecord {
self.clone().into_log_record()
}
fn into_log_record(self) -> LogRecord {
let mut record = LogRecord::new(self.severity, self.message);
record.attributes = self.fields;
if let Some(trace) = self.trace {
record.trace_id = Some(trace.trace_id);
record.span_id = Some(trace.span_id);
record.flags = u32::from(trace.sampled);
}
if let Some(file) = self.file {
record
.attributes
.push(KeyValue::new("code.file.path", file));
}
if let Some(line) = self.line {
record
.attributes
.push(KeyValue::new("code.line.number", i64::from(line)));
}
if let Some(name) = thread::current().name() {
record
.attributes
.push(KeyValue::new("thread.name", name.to_owned()));
}
record.attributes.extend(
resolve_entry_point(|| self.entry_point)
.into_attributes()
.into_iter()
.map(|(key, value)| KeyValue::new(key, value)),
);
record
}
pub(crate) fn to_report(&self, app_crates: &[String]) -> Report {
let mut report = match &self.error {
Some(error) => error.to_report(),
None => Report::from_message(self.message.clone(), self.level(), Location::caller()),
};
report.set_location(self.location_frame(app_crates));
let context = self.report_context();
if !context.is_empty() {
report.set_context("log", Value::Object(context.into_iter().collect()));
}
report.entry_point = Some(resolve_entry_point(|| self.entry_point.clone()));
report
}
fn location_frame(&self, app_crates: &[String]) -> Frame {
Frame {
file: self.file.clone().unwrap_or_else(|| "<unknown>".to_owned()),
line_number: self.line.unwrap_or(0),
column_number: None,
method: None,
class: None,
is_application_frame: self
.file
.as_deref()
.is_some_and(|file| is_application_file(Path::new(file), app_crates)),
instruction_addr: None,
}
}
fn report_context(&self) -> BTreeMap<String, Value> {
let mut context = fields_to_json(&self.fields);
if let Some(error) = &self.error
&& !self.message.is_empty()
&& self.message != error.message
{
context.insert("message".to_owned(), Value::from(self.message.clone()));
}
context
}
}
#[cfg(test)]
mod tests {
use std::fmt;
use flareapp_otlp::{AnyValue, Resource};
use super::*;
use crate::scope::with_scope;
use crate::test_support::{attribute, in_queue_span, serial};
fn line() -> LogLine {
let mut line = LogLine::new("shop::checkout", "payment declined", Severity::Warn);
line.fields = vec![KeyValue::new("order_id", 7_i64)];
line.file = Some("src/checkout.rs".to_owned());
line.line = Some(42);
line
}
fn report_json(line: &LogLine) -> Value {
let mut report = line.to_report(&[]);
report.resolve_entry_point();
let resource = Resource::new(Vec::new());
let body = report.resolve_frames(false).encode(&resource).unwrap();
serde_json::from_slice(&body).unwrap()
}
#[test]
fn log_records_have_the_message_and_severity() {
let record = line().to_log_record();
assert_eq!(record.severity_number, Severity::Warn);
assert_eq!(record.body, "payment declined");
}
#[test]
fn log_records_have_the_fields() {
let record = line().to_log_record();
assert_eq!(
attribute(&record.attributes, "order_id"),
Some(&AnyValue::Int(7))
);
}
#[test]
fn log_records_have_the_source_location() {
let record = line().to_log_record();
assert_eq!(
attribute(&record.attributes, "code.file.path"),
Some(&AnyValue::String("src/checkout.rs".to_owned()))
);
assert_eq!(
attribute(&record.attributes, "code.line.number"),
Some(&AnyValue::Int(42))
);
}
#[test]
fn log_records_have_the_trace_context() {
let mut line = line();
line.trace = Some(TraceContext {
trace_id: TraceId::random(),
span_id: SpanId::random(),
sampled: true,
});
let record = line.to_log_record();
assert_eq!(record.trace_id, line.trace.map(|trace| trace.trace_id));
assert_eq!(record.span_id, line.trace.map(|trace| trace.span_id));
assert_eq!(record.flags, 1);
}
fn log_record_in_a_web_scope() -> LogRecord {
let entry_point =
EntryPoint::web("https://shop.test/users/7").handler_identifier("GET /users/{id}");
with_scope(
|scope| scope.set_entry_point(entry_point),
|| line().to_log_record(),
)
}
#[test]
fn log_records_have_the_entry_point_type_of_the_scope() {
let record = log_record_in_a_web_scope();
assert_eq!(
attribute(&record.attributes, "flare.entry_point.type"),
Some(&AnyValue::String("web".to_owned()))
);
}
#[test]
fn log_records_have_the_handler_identifier_of_the_scope() {
let record = log_record_in_a_web_scope();
assert_eq!(
attribute(&record.attributes, "flare.entry_point.handler.identifier"),
Some(&AnyValue::String("GET /users/{id}".to_owned()))
);
}
#[test]
fn log_records_have_the_entry_point_of_their_span() {
let mut line = line();
line.entry_point = Some(EntryPoint::queue("send-invoice"));
let record = line.to_log_record();
assert_eq!(
attribute(&record.attributes, "flare.entry_point.type"),
Some(&AnyValue::String("queue".to_owned()))
);
}
#[test]
fn log_records_outside_any_work_are_commands() {
let _serial = serial();
let record = line().to_log_record();
assert_eq!(
attribute(&record.attributes, "flare.entry_point.type"),
Some(&AnyValue::String("cli".to_owned()))
);
}
#[test]
fn log_records_outside_any_work_are_rust_binaries() {
let _serial = serial();
let record = line().to_log_record();
assert_eq!(
attribute(&record.attributes, "flare.entry_point.handler.type"),
Some(&AnyValue::String("rust_binary".to_owned()))
);
}
#[test]
fn reports_from_log_lines_get_the_entry_point_of_their_span() {
let mut line = line();
line.entry_point = Some(EntryPoint::queue("send-invoice"));
let json = report_json(&line);
assert_eq!(json["attributes"]["flare.entry_point.type"], "queue");
}
#[test]
fn reports_from_log_lines_without_a_span_entry_point_ignore_the_current_span() {
let _serial = serial();
let json = in_queue_span(|| report_json(&line()));
assert_eq!(json["attributes"]["flare.entry_point.type"], "cli");
}
#[test]
fn reports_that_never_looked_for_a_span_use_the_current_span() {
let _serial = serial();
let entry_point = in_queue_span(|| {
let mut report = Report::from_message("x".to_owned(), Level::Error, Location::caller());
report.resolve_entry_point();
report.entry_point
});
assert_eq!(entry_point, Some(EntryPoint::queue("send-invoice")));
}
#[test]
fn reports_have_the_message_and_level() {
let json = report_json(&line());
assert_eq!(json["exceptionClass"], "Log");
assert_eq!(json["message"], "payment declined");
assert_eq!(json["level"], "warning");
}
#[test]
fn reports_use_the_log_location_as_their_frame() {
let json = report_json(&line());
assert_eq!(json["stacktrace"][0]["file"], "src/checkout.rs");
assert_eq!(json["stacktrace"][0]["lineNumber"], 42);
}
#[test]
fn reports_have_the_fields_as_context() {
let json = report_json(&line());
assert_eq!(
json["attributes"]["context.custom"]["log"],
json!({ "order_id": 7 })
);
}
#[derive(Debug)]
struct ForeignKeyViolation;
impl fmt::Display for ForeignKeyViolation {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("insert violates foreign key constraint")
}
}
impl Error for ForeignKeyViolation {}
#[derive(Debug)]
enum QueryFailed {
Database(ForeignKeyViolation),
}
impl fmt::Display for QueryFailed {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("error returned from database")
}
}
impl Error for QueryFailed {
fn source(&self) -> Option<&(dyn Error + 'static)> {
let Self::Database(violation) = self;
Some(violation)
}
}
fn line_with_error() -> LogLine {
let mut line = line();
line.error = Some(LoggedError::new(&QueryFailed::Database(
ForeignKeyViolation,
)));
line
}
#[test]
fn reports_of_lines_with_an_error_report_the_error() {
let json = report_json(&line_with_error());
assert_eq!(
(&json["exceptionClass"], &json["message"], &json["level"]),
(
&json!("Database"),
&json!("error returned from database"),
&Value::Null
)
);
}
#[test]
fn reports_of_lines_with_an_error_keep_the_message_as_context() {
let json = report_json(&line_with_error());
assert_eq!(
json["attributes"]["context.custom"]["log"],
json!({ "message": "payment declined", "order_id": 7 })
);
}
#[test]
fn reports_of_lines_with_an_error_list_its_causes_as_context() {
let json = report_json(&line_with_error());
assert_eq!(
json["attributes"]["context.custom"]["error"],
json!({ "sources": [{
"class": "ForeignKeyViolation",
"message": "insert violates foreign key constraint",
}] })
);
}
#[test]
fn reports_of_lines_with_an_error_without_causes_have_no_error_context() {
let mut line = line();
line.error = Some(LoggedError::new(&ForeignKeyViolation));
let json = report_json(&line);
assert_eq!(json["attributes"]["context.custom"]["error"], Value::Null);
}
#[test]
fn reports_of_lines_from_a_dependency_have_no_application_frame() {
let mut line = line();
line.file = Some(
"/home/me/.cargo/registry/src/index.crates.io-1949cf8c6b5b557f/tracing-panic-0.1.2/src/lib.rs"
.to_owned(),
);
let json = report_json(&line);
assert_eq!(json["stacktrace"][0]["isApplicationFrame"], false);
}
#[test]
fn reports_of_lines_from_the_app_have_an_application_frame() {
let json = report_json(&line());
assert_eq!(json["stacktrace"][0]["isApplicationFrame"], true);
}
#[test]
fn reports_without_a_file_have_no_application_frame() {
let mut line = line();
line.file = None;
let json = report_json(&line);
assert_eq!(json["stacktrace"][0]["isApplicationFrame"], false);
}
}