flareapp 0.2.0

Report errors, logs and traces from Rust applications to Flare.
Documentation
//! Sends errors, logs and traces from Rust applications to [Flare](https://flareapp.io).
//!
//! # Getting started
//!
//! ```no_run
//! // Reads the API key from the `FLARE_KEY` environment variable or `.env` file.
//! let _flare = flareapp::init(flareapp::config!().environment("production"));
//!
//! // Your application runs here. When `_flare` is dropped, queued data is sent
//! // before the process exits.
//! ```
//!
//! You can also use `#[flareapp::main]`. The attribute starts the Flare client,
//! and also reports an error that `main` returns:
//!
//! ```no_run
//! #[flareapp::main(environment = "production")]
//! fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     // Your application runs here.
//!     Ok(())
//! }
//! ```
//!
//! # Reporting errors
//!
//! ```no_run
//! use flareapp::{Level, User};
//! use serde_json::json;
//!
//! flareapp::configure_scope(|scope| scope.set_user(User::new("42").email("a@b.c")));
//! flareapp::glow("cart updated", Level::Info, json!({ "items": 3 }));
//!
//! if let Err(error) = std::fs::read_to_string("orders.csv") {
//!     flareapp::report_error(&error);
//! }
//!
//! flareapp::report_message("Stock low", Level::Warning);
//! ```
//!
//! When the `panic` feature is on, the Flare client also reports panics.
//!
//! Keep the guard in a named variable like `_flare`. `let _ = flareapp::init(…)`
//! drops the guard right away and stops the Flare client.
//!
//! # How data is sent
//!
//! The Flare client sends logs and traces as OTLP, the standard format of
//! OpenTelemetry, encoded as protobuf. [`Config::otlp_protocol`] switches to
//! OTLP/JSON. The worker thread, a background thread, collects the data and sends
//! the data in batches, so your code never waits for the network. When a request
//! fails, the worker thread tries the request again up to 3 times, and waits
//! longer before each new try.
//!
//! # Features
//!
//! - `ureq` (default): sends data with the `ureq` HTTP client. Without this
//!   feature, pass your own [`Transport`] to [`Config::transport`].
//! - `backtrace` (default): adds stack traces to reports. Without this feature, a
//!   report has only the line where the app made the report.
//! - `panic` (default): reports panics. Turns on `backtrace`.
//! - `macros` (default): adds the `#[flareapp::main]` attribute.
//! - `dotenv` (default): reads the settings of [`Config::new`] from the `.env`
//!   file, when the environment does not set them.
//! - `tracing`: sends `tracing` spans as traces, and events as logs and
//!   breadcrumbs. sqlx queries become query spans. See the `flareapp::tracing`
//!   module.
//! - `log`: sends `log` records as logs and breadcrumbs. See the `flareapp::log`
//!   module. You need this feature only when your app does not use `tracing`.
//! - `tower`: adds middleware that gives each request its own scope and root span.
//!   See the `flareapp::tower` module.
//! - `axum`: turns on `tower`, and adds the route name (`GET /users/{id}`) for
//!   axum apps. The `tower` middleware also detects axum without this feature.
//! - `actix`: adds actix-web middleware that gives each request its own scope and
//!   root span, and reports server errors. See the `flareapp::actix` module. Turns
//!   on `backtrace`.
//! - `reqwest`: continues traces in outgoing reqwest calls. See the
//!   `flareapp::reqwest` module.
//! - `sqlx-postgres`, `sqlx-mysql`, `sqlx-sqlite`: add a sqlx pool whose query
//!   spans name the database and show failed queries. See the `flareapp::sqlx`
//!   module.
//! - `anyhow`: reports `anyhow::Error`. See the `flareapp::anyhow` module. Turns on
//!   `backtrace`.

mod main_error;
#[cfg(feature = "ureq")]
mod ureq;

use std::panic::Location;

pub use flareapp_core::{
    Config, EntryPoint, Guard, Level, OtlpProtocol, Report, ReportId, ReportableError, Request,
    Response, Scope, ScopeFutureExt, Signal, Transport, TransportError, User, WithScope,
    configure_scope, flush, glow, with_scope,
};
#[cfg(feature = "macros")]
pub use flareapp_macros::main;

/// Helpers for `#[flareapp::main]`. This module is not part of the public API.
#[doc(hidden)]
pub mod __private {
    pub use flareapp_core::workspace_root;

    pub use crate::main_error::{MainError, ReportMainError};

    /// Returns the first value that is set and not blank, or an empty string.
    pub fn first_set(values: &[Option<&'static str>]) -> &'static str {
        values
            .iter()
            .flatten()
            .map(|value| value.trim())
            .find(|value| !value.is_empty())
            .unwrap_or("")
    }
}

/// Sends `tracing` spans and events to Flare. See the `flareapp-tracing` crate.
#[cfg(feature = "tracing")]
pub mod tracing {
    pub use flareapp_tracing::{FlareLayer, SpanExt, current_traceparent, layer};
}

/// Sends `log` records to Flare. See the `flareapp-log` crate.
#[cfg(feature = "log")]
pub mod log {
    pub use flareapp_log::Logger;
}

/// Adds Flare to tower servers like axum. See the `flareapp-tower` crate.
#[cfg(feature = "tower")]
pub mod tower {
    pub use flareapp_tower::{RequestLayer, RequestService, ResponseFuture, layer};
}

/// Adds Flare to actix-web apps. See the `flareapp-actix` crate.
#[cfg(feature = "actix")]
pub mod actix {
    pub use flareapp_actix::{Middleware, MiddlewareService, ResponseFuture, middleware};
}

/// Continues traces in outgoing reqwest calls. See the `flareapp-reqwest` crate.
#[cfg(feature = "reqwest")]
pub mod reqwest {
    pub use flareapp_reqwest::TracePropagation;
}

/// Sends sqlx queries as query spans, with the database and the errors. See the
/// `flareapp-sqlx` crate.
#[cfg(any(
    feature = "sqlx-postgres",
    feature = "sqlx-mysql",
    feature = "sqlx-sqlite"
))]
pub mod sqlx {
    pub use flareapp_sqlx::{Pool, PoolConnection, TracedDatabase, Transaction};
}

/// Reports `anyhow` errors. See the `flareapp-anyhow` crate.
#[cfg(feature = "anyhow")]
pub mod anyhow {
    pub use flareapp_anyhow::{report, report_with};
}

/// Starts the Flare client and returns a guard that keeps the client running.
///
/// Without an API key, the Flare client stays disabled. All functions of this
/// crate still work, but they do nothing.
///
/// Keep the guard until your program ends. When you drop the guard, the guard
/// sends the queued data and stops the Flare client.
///
/// Do not write `let _ = flareapp::init(…)`. That line drops the guard right away
/// and stops the Flare client.
///
/// # Examples
///
/// ```no_run
/// let _flare = flareapp::init(flareapp::config!());
/// ```
pub fn init(config: Config) -> Guard {
    #[cfg(feature = "ureq")]
    let config = config.default_transport(ureq::UreqTransport::new);

    let guard = flareapp_core::init(config);

    #[cfg(feature = "panic")]
    flareapp_panic::install();

    guard
}

/// Reports an error that your code handled.
///
/// The exception class is the Rust type of the error, and the message is the
/// `Display` output of the error.
///
/// You can report every error type that does not borrow data, and every
/// `dyn Error`. [`ReportableError`] explains why.
///
/// Returns the tracking id of the report, or `None` when the Flare client is
/// disabled or `before_send` dropped the report. Also returns `None` when the
/// queue was full or the worker thread had stopped, because the client then did
/// not queue the report.
#[track_caller]
pub fn report_error<E: ReportableError + ?Sized>(error: &E) -> Option<ReportId> {
    report_error_with(error, |_| {})
}

/// Reports an error, and lets you change the report before it is sent.
///
/// Returns the tracking id of the report, or `None` when the Flare client is
/// disabled or `before_send` dropped the report. Also returns `None` when the
/// queue was full or the worker thread had stopped, because the client then did
/// not queue the report.
///
/// # Examples
///
/// ```no_run
/// # let error = std::io::Error::other("timeout");
/// flareapp::report_error_with(&error, |report| {
///     report.set_context("payment", serde_json::json!({ "provider": "mollie" }));
/// });
/// ```
#[track_caller]
pub fn report_error_with<E, F>(error: &E, configure: F) -> Option<ReportId>
where
    E: ReportableError + ?Sized,
    F: FnOnce(&mut Report),
{
    capture_and_send(|location| Report::from_error(error, location), configure)
}

/// Reports a message, like a log line that needs attention.
///
/// Returns the tracking id of the report, or `None` when the Flare client is
/// disabled or `before_send` dropped the report. Also returns `None` when the
/// queue was full or the worker thread had stopped, because the client then did
/// not queue the report.
#[track_caller]
pub fn report_message<M: Into<String>>(message: M, level: Level) -> Option<ReportId> {
    capture_and_send(
        |location| Report::from_message(message, level, location),
        |_| {},
    )
}

/// Builds a report, adds its stack trace, lets `configure` change it, and sends it.
///
/// Every public report function in this crate calls this function. This function
/// calls `make_report` only when the Flare client is enabled, and passes it the
/// place where the app called the public function.
#[track_caller]
fn capture_and_send<M, C>(make_report: M, configure: C) -> Option<ReportId>
where
    M: FnOnce(&'static Location<'static>) -> Report,
    C: FnOnce(&mut Report),
{
    let client = flareapp_core::current()?;
    let location = Location::caller();
    let mut report = make_report(location);

    #[cfg(feature = "backtrace")]
    report.set_frames(flareapp_backtrace::capture(&client));

    configure(&mut report);

    client.send_report(report)
}

/// Creates a [`Config`] that already has the name and version of your crate.
///
/// The name and version come from the `Cargo.toml` of the crate that calls this
/// macro, not from the Flare client. The macro also marks the frames of your crate
/// as application code, sets the application path to the folder of your
/// `Cargo.toml`, and finds the root of your Cargo workspace.
///
/// The macro also reads the git commit while your app compiles, from the first of
/// these variables that is set: `FLARE_GIT_HASH`, `GITHUB_SHA` (GitHub Actions),
/// `CI_COMMIT_SHA` (GitLab), `CIRCLE_SHA1` (`CircleCI`) or `BITBUCKET_COMMIT`
/// (Bitbucket). A Docker build does not see these variables, so pass the commit
/// with `--build-arg` and an `ARG FLARE_GIT_HASH` line in the `Dockerfile`.
///
/// When no variable is set, the Flare client runs `git` at startup to read the
/// commit. This works only when the folder of your `Cargo.toml` exists on the
/// machine that runs the app.
///
/// # Examples
///
/// ```
/// let config = flareapp::config!().environment("production");
/// ```
#[macro_export]
macro_rules! config {
    () => {
        $crate::Config::new()
            .service_name(::core::env!("CARGO_PKG_NAME"))
            .service_version(::core::env!("CARGO_PKG_VERSION"))
            .app_crate(::core::env!("CARGO_CRATE_NAME"))
            .application_path(::core::env!("CARGO_MANIFEST_DIR"))
            .workspace_root($crate::__private::workspace_root(
                ::core::env!("CARGO_MANIFEST_DIR"),
                ::core::file!(),
            ))
            .git_hash($crate::__private::first_set(&[
                ::core::option_env!("FLARE_GIT_HASH"),
                ::core::option_env!("GITHUB_SHA"),
                ::core::option_env!("CI_COMMIT_SHA"),
                ::core::option_env!("CIRCLE_SHA1"),
                ::core::option_env!("BITBUCKET_COMMIT"),
            ]))
    };
}

#[cfg(test)]
mod config_tests {
    use std::path::Path;

    #[test]
    fn config_finds_the_workspace_root() {
        // This crate lives in `crates/flareapp` of the workspace.
        let root = Path::new(env!("CARGO_MANIFEST_DIR"))
            .parent()
            .and_then(Path::parent)
            .unwrap();

        let found = crate::__private::workspace_root(env!("CARGO_MANIFEST_DIR"), file!());

        assert_eq!(Path::new(&found), root);
    }

    #[test]
    fn first_set_skips_missing_and_blank_values() {
        let first_set = crate::__private::first_set;

        assert_eq!(
            first_set(&[None, Some(" "), Some("abc"), Some("def")]),
            "abc"
        );
    }

    #[test]
    fn first_set_is_empty_when_no_value_is_set() {
        let first_set = crate::__private::first_set;

        assert_eq!(first_set(&[None, Some("")]), "");
    }
}

#[cfg(test)]
#[cfg(feature = "ureq")]
mod tests {
    use std::time::Duration;

    use flareapp_core::{Client, StartError};
    use flareapp_otlp::{LogRecord, Severity};

    use super::*;

    #[test]
    #[ignore = "sends a real log to Flare; needs FLARE_KEY"]
    fn sends_a_log_to_flare() {
        let config = Config::new()
            .debug(true)
            .default_transport(ureq::UreqTransport::new);
        let client = match Client::start(config) {
            Ok(client) => client,
            Err(StartError::NoApiKey) => panic!("set FLARE_KEY to run this test"),
            Err(error) => panic!("Flare did not start: {error}"),
        };

        client.send_log(
            module_path!(),
            LogRecord::new(
                Severity::Info,
                "Hello from the flareapp Rust client test suite".to_owned(),
            ),
        );

        assert!(client.flush(Duration::from_secs(15)));
    }
}