flareapp 0.3.0

Report errors, logs and traces from Rust applications to Flare.
Documentation
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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
//! 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`.
//! - `opentelemetry`: sends the spans of the OpenTelemetry SDK, for apps and
//!   frameworks that make their spans with `tracing-opentelemetry`. See the
//!   `flareapp::opentelemetry` module.
//! - `laravel`: adds a service provider for Laravel for Rust, which sends the
//!   errors, logs and traces of the app. See the `flareapp::laravel` module. Turns
//!   on `tracing` and `opentelemetry`, and needs Rust 1.99.

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};
}

/// Sends the spans of the OpenTelemetry SDK to Flare. See the
/// `flareapp-opentelemetry` crate.
#[cfg(feature = "opentelemetry")]
pub mod opentelemetry {
    pub use flareapp_opentelemetry::{FlareSpanProcessor, sampler, tracer_provider};
}

/// Connects Flare to Laravel for Rust. See the `flareapp-laravel` crate.
#[cfg(feature = "laravel")]
pub mod laravel {
    pub use flareapp_laravel::{Flare, FlareServiceProvider};

    /// Returns the Flare service provider for a Laravel app.
    ///
    /// The provider starts the Flare client with `config` when the application
    /// registers its providers, or reuses the Flare client if the client is already
    /// running. This function gives the config the default transport of
    /// `flareapp`, like [`init`](crate::init) does.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// fn main() -> std::process::ExitCode {
    ///     laravel::Application::configure()
    ///         .with_providers(|providers| {
    ///             providers.add(flareapp::laravel::provider(flareapp::config!()));
    ///         })
    ///         .run()
    /// }
    /// ```
    pub fn provider(config: crate::Config) -> FlareServiceProvider {
        #[cfg(feature = "ureq")]
        let config = config.default_transport(crate::ureq::UreqTransport::new);

        FlareServiceProvider::new(config)
    }
}

/// 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)));
    }
}