aether/
scoped.rs

1use std::sync::Mutex;
2
3use crate::{endpoint::EndpointExt, EndpointSuper, LOGGER};
4
5lazy_static::lazy_static! {
6    pub(crate) static ref SCOPE: Mutex<Option<Box<dyn EndpointExt>>> = Mutex::new(None);
7}
8
9#[doc(hidden)]
10pub fn impl_slog(message: String) {
11    let scope_guard = SCOPE.lock().unwrap();
12    let scope = scope_guard
13        .as_ref()
14        .expect("Tried using scoped log outside of a log scope.");
15
16    let output = scope.fmt_message(message);
17
18    let mut guard = LOGGER.lock().unwrap();
19    let logger = guard.as_mut().expect("Uninitialized logger. Did you forget to call `aether::init` or did you drop the `KeepAlive` object early?");
20    logger.log(scope.endpoint_hash(), output);
21}
22
23/// Starts a log scope within the closure provided.
24pub fn scoped<EP: EndpointSuper + std::hash::Hash>(endpoint: EP, f: impl FnOnce()) {
25    let mut scope_guard = SCOPE.lock().unwrap();
26    let prev_scope = scope_guard.replace(Box::new(endpoint));
27    std::mem::drop(scope_guard);
28    f();
29    let mut scope_guard = SCOPE.lock().unwrap();
30    *scope_guard = prev_scope;
31}