redux_rs/middlewares/
logger.rs

1use crate::{MiddleWare, StoreApi};
2use async_trait::async_trait;
3use log::{log, Level};
4use std::fmt::Debug;
5use std::sync::Arc;
6
7/// A middleware which logs every single action that has been dispatched to the store
8/// We're using the `log` crate to achieve the logging, the log level can be set
9///
10/// ## Usage:
11/// ```
12/// # #[derive(Default)]
13/// # struct EmptyStore;
14/// #
15/// # #[derive(Debug)]
16/// # struct LogableAction(&'static str);
17/// #
18/// # fn reducer(store: EmptyStore, _action: LogableAction) -> EmptyStore {
19/// #     store
20/// # }
21/// use log::Level;
22/// use redux_rs::{
23///     middlewares::logger::LoggerMiddleware,
24///     Store
25/// };
26/// # async fn async_test() {
27/// // Setup the logger middleware with default "Debug" log level
28/// let logger_middleware = LoggerMiddleware::new(Level::Debug);
29///
30/// // Create a new store and wrap it with the logger middleware
31/// let store = Store::new(reducer).wrap(logger_middleware).await;
32/// # }
33/// ```
34pub struct LoggerMiddleware {
35    log_level: Level,
36}
37
38impl LoggerMiddleware {
39    /// Crate a new logger.
40    /// LogLevel is the level that the logs will be output with
41    pub fn new(log_level: Level) -> Self {
42        LoggerMiddleware { log_level }
43    }
44}
45
46#[async_trait]
47impl<State, Action, Inner> MiddleWare<State, Action, Inner> for LoggerMiddleware
48where
49    State: Send + 'static,
50    Action: Debug + Send + 'static,
51    Inner: StoreApi<State, Action> + Send + Sync,
52{
53    async fn dispatch(&self, action: Action, inner: &Arc<Inner>) {
54        // Log the action
55        log!(self.log_level, "Action: {:?}", action);
56
57        // Continue dispatching the action
58        inner.dispatch(action).await
59    }
60}