├── .gitignore ├── .github └── workflows │ └── publish.yml ├── Cargo.toml ├── Cargo.lock ├── README.md ├── LICENSE └── src └── lib.rs /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | -------------------------------------------------------------------------------- /.github/workflows/publish.yml: -------------------------------------------------------------------------------- 1 | name: GitHub Actions Demo 2 | run-name: ${{ github.actor }} is deploying to crates.io 🚀 3 | on: [push] 4 | jobs: 5 | Publish: 6 | runs-on: ubuntu-latest 7 | steps: 8 | - uses: actions/checkout@v3 9 | - uses: actions-rs/toolchain@v1 10 | with: 11 | toolchain: stable 12 | override: true 13 | - uses: katyo/publish-crates@v2 14 | with: 15 | registry-token: ${{ secrets.CARGO_REGISTRY_TOKEN }} -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "breadcrumbs" 3 | version = "0.1.5" 4 | edition = "2021" 5 | authors = ["Michael Reeves "] 6 | license = "Apache-2.0" 7 | repository = "https://github.com/IntegralPilot/breadcrumbs-rs" 8 | categories = ["development-tools::debugging"] 9 | readme = "README.md" 10 | documentation = "https://docs.rs/breadcrumbs" 11 | description = "A beautiful, tiny traceback and logging library supporting #![no_std] rust." 12 | 13 | 14 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 15 | 16 | [dependencies] 17 | spin = "0.9.8" 18 | 19 | [dependencies.lazy_static] 20 | version = "1.0" 21 | features = ["spin_no_std"] 22 | -------------------------------------------------------------------------------- /Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | version = 3 4 | 5 | [[package]] 6 | name = "autocfg" 7 | version = "1.1.0" 8 | source = "registry+https://github.com/rust-lang/crates.io-index" 9 | checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" 10 | 11 | [[package]] 12 | name = "breadcrumbs" 13 | version = "0.1.5" 14 | dependencies = [ 15 | "lazy_static", 16 | "spin 0.9.8", 17 | ] 18 | 19 | [[package]] 20 | name = "lazy_static" 21 | version = "1.4.0" 22 | source = "registry+https://github.com/rust-lang/crates.io-index" 23 | checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" 24 | dependencies = [ 25 | "spin 0.5.2", 26 | ] 27 | 28 | [[package]] 29 | name = "lock_api" 30 | version = "0.4.11" 31 | source = "registry+https://github.com/rust-lang/crates.io-index" 32 | checksum = "3c168f8615b12bc01f9c17e2eb0cc07dcae1940121185446edc3744920e8ef45" 33 | dependencies = [ 34 | "autocfg", 35 | "scopeguard", 36 | ] 37 | 38 | [[package]] 39 | name = "scopeguard" 40 | version = "1.2.0" 41 | source = "registry+https://github.com/rust-lang/crates.io-index" 42 | checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" 43 | 44 | [[package]] 45 | name = "spin" 46 | version = "0.5.2" 47 | source = "registry+https://github.com/rust-lang/crates.io-index" 48 | checksum = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d" 49 | 50 | [[package]] 51 | name = "spin" 52 | version = "0.9.8" 53 | source = "registry+https://github.com/rust-lang/crates.io-index" 54 | checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67" 55 | dependencies = [ 56 | "lock_api", 57 | ] 58 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # breadcrumbs 2 | Breadcrumbs is a beautiful, tiny traceback and logging library for Rust that offers seamless integration with `#![no_std]`, multi-threading and concurrency. 3 | 4 | ## Features 5 | - Beautifully-formatted traceback of logs (supporting `Display` and `Debug`) 6 | - Dynamic log levels 7 | - Dynamic log channels 8 | - Seamless integration with `#![no_std]` 9 | - Multi-threading and concurrent logging supported with no special syntax 10 | - Easy-to-use macros 11 | - Support for listeners to be notified of new logs 12 | 13 | ## Usage 14 | Add the following to your `Cargo.toml`: 15 | ```toml 16 | [dependencies] 17 | breadcrumbs = "0.1.5" 18 | ``` 19 | 20 | Then, initalize `breadcrumbs` once in your `main.rs` or `lib.rs`: 21 | ```rust 22 | use breadcrumbs::init; 23 | 24 | init!(); 25 | ``` 26 | 27 | You can set a custom log listener with ease by implementing the `LogListener` trait: 28 | ```rust 29 | use breadcrumbs::{init, LogListener, Log, LogLevel}; 30 | 31 | struct MyLogListener; 32 | 33 | impl LogListener for MyLogListener { 34 | fn on_log(&mut self, log: Log) { 35 | if log.level.is_at_least(LogLevel::Warn) { 36 | println!("{}", log); 37 | } else { 38 | // 💡 New in 0.1.5 - Remove unnecessary logs to save memory 39 | // Useful in embedded usecases 40 | log.remove(); 41 | } 42 | } 43 | } 44 | 45 | init!(MyLogListener); 46 | ``` 47 | 48 | Then, simply use the `log!` macro from or its variants from anywhere to log messages: 49 | ```rust 50 | use breadcrumbs::{log, log_level, log_channel, LogLevel}; 51 | 52 | // A basic log message 53 | log!("Hello, world!"); 54 | 55 | // A log message with a custom level 56 | log_level!(LogLevel::Info, "Test log message"); 57 | 58 | // A log message with a custom channel 59 | log_channel!("test_channel", "Test log message"); 60 | 61 | // A log message with a custom channel and level 62 | log!(LogLevel::Info, "test_channel", "Test log message"); 63 | ``` 64 | 65 | Access a traceback of log messages from anywhere with the `traceback!` macro or its variants: 66 | ```rust 67 | use breadcrumbs::{traceback, traceback_channel, traceback_level, LogLevel}; 68 | 69 | // A basic traceback, fetching all logged messages 70 | let t = traceback!(); 71 | 72 | // A traceback with a custom channel, fetching messages in this channel 73 | let t = traceback_channel!("my-channel"); 74 | 75 | // A traceback with a custom level, fetching messages of this level or higher 76 | let traceback = traceback_level!(LogLevel::Warn); 77 | 78 | // A traceback with a custom channel and level, fetching messages in this channel of this level or higher 79 | let traceback = traceback!(LogLevel::Warn, "test_channel"); 80 | ``` 81 | 82 | `Traceback` and `Log` objects beautifully implement `Display` and `Debug`: 83 | ```rust 84 | use breadcrumbs::traceback; 85 | 86 | let t = traceback!(); 87 | println!("{}", t); 88 | println!("{:?}", t); 89 | ``` 90 | 91 | ## Example 92 | 93 | ```rust 94 | use breadcrumbs::{init, log, log_level, log_channel, traceback, LogLevel, LogListener, Log}; 95 | 96 | struct MyLogListner; 97 | 98 | impl LogListener for MyLogListner { 99 | fn on_log(&mut self, log: Log) { 100 | if log.level.is_at_least(LogLevel::Warn) { 101 | println!("{}", log); 102 | } 103 | } 104 | } 105 | 106 | fn main() { 107 | init!(MyLogListner); 108 | 109 | log!("Hello, world!"); 110 | log_level!(LogLevel::Info, "Test log message"); 111 | log_channel!("test_channel", "Test log message"); 112 | log!(LogLevel::Warn, "test_channel", "Test log message"); 113 | 114 | let t = traceback!(); 115 | println!("Fatal Error! Traceback:\n{}", t); 116 | } 117 | ``` 118 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #![no_std] 2 | 3 | //! # breadcrumbs 4 | //! Breadcrumbs is a beautiful, tiny traceback and logging library for Rust that offers seamless integration with `#![no_std]`, `#[no_panic]` multi-threading and concurrency. 5 | //! 6 | //! ## Features 7 | //! - Beautifully-formatted traceback of logs (supporting `Display` and `Debug`) 8 | //! - Dynamic log levels 9 | //! - Dynamic log channels 10 | //! - Seamless integration with `#![no_std]` and `#[no_panic]` 11 | //! - Multi-threading and concurrent logging with no special syntax 12 | //! - Easy-to-use macros 13 | //! - Support for listeners to be notified of new logs 14 | 15 | // Import the necessary crates 16 | extern crate alloc; 17 | use alloc::{ 18 | vec::Vec, 19 | sync::Arc, 20 | boxed::Box, 21 | string::String, 22 | format 23 | }; 24 | use lazy_static::lazy_static; 25 | use spin::Mutex; 26 | 27 | /// Enum representing different log levels. 28 | #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Debug)] 29 | pub enum LogLevel { 30 | Verbose, 31 | Info, 32 | Warn, 33 | Error, 34 | Critical, 35 | } 36 | 37 | impl Default for LogLevel { 38 | fn default() -> Self { 39 | LogLevel::Info 40 | } 41 | } 42 | 43 | impl core::fmt::Display for LogLevel { 44 | fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { 45 | let level_str = match self { 46 | LogLevel::Verbose => "Verbose", 47 | LogLevel::Info => "Info", 48 | LogLevel::Warn => "Warn", 49 | LogLevel::Error => "Error", 50 | LogLevel::Critical => "Critical", 51 | }; 52 | write!(f, "{}", level_str) 53 | } 54 | } 55 | impl LogLevel { 56 | /// Checks if the current log level is at least as severe as the provided level. 57 | /// ```rust 58 | /// use breadcrumbs::LogLevel; 59 | /// let log_level = LogLevel::Info; 60 | /// assert!(log_level.is_at_least(LogLevel::Info)); 61 | /// assert!(log_level.is_at_least(LogLevel::Verbose)); 62 | /// assert!(!log_level.is_at_least(LogLevel::Warn)); 63 | /// ``` 64 | pub fn is_at_least(&self, level: LogLevel) -> bool { 65 | match level { 66 | LogLevel::Verbose => true, 67 | LogLevel::Info => self != &LogLevel::Verbose, 68 | LogLevel::Warn => self != &LogLevel::Verbose && self != &LogLevel::Info, 69 | LogLevel::Error => self != &LogLevel::Verbose && self != &LogLevel::Info && self != &LogLevel::Warn, 70 | LogLevel::Critical => self == &LogLevel::Critical, 71 | } 72 | } 73 | 74 | pub fn from_str(level: &str) -> LogLevel { 75 | match level { 76 | "Verbose" => LogLevel::Verbose, 77 | "Info" => LogLevel::Info, 78 | "Warn" => LogLevel::Warn, 79 | "Error" => LogLevel::Error, 80 | "Critical" => LogLevel::Critical, 81 | _ => LogLevel::Info, 82 | } 83 | } 84 | } 85 | 86 | /// Represents a log entry. 87 | /// `Log` beautifully implements `Display` for easy printing. 88 | /// ```rust 89 | /// use breadcrumbs::Log; 90 | /// let log = Log::new(String::from("test_channel"), breadcrumbs::LogLevel::Info, String::from("Test log message")); 91 | /// assert_eq!(format!("{}", log), "[test_channel/Info] Test log message"); 92 | /// ``` 93 | #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Debug)] 94 | pub struct Log { 95 | pub channel: String, 96 | pub level: LogLevel, 97 | pub message: String, 98 | } 99 | 100 | impl core::fmt::Display for Log { 101 | fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { 102 | if self.channel != "" { 103 | return write!(f, "[{}/{}] {}", self.channel, self.level, self.message); 104 | } else { 105 | return write!(f, "[{}] {}", self.level, self.message) 106 | } 107 | } 108 | } 109 | 110 | impl Log { 111 | /// Creates a new log entry. 112 | pub fn new(channel: String, level: LogLevel, message: String) -> Log { 113 | Log { 114 | channel, 115 | level, 116 | message, 117 | } 118 | } 119 | /// Removes the log from the stored traceback of logs. 120 | /// This log will not use up memory or be printed by the traceback macros. 121 | /// Useful in embedded systems where memory is limited. 122 | /// 123 | /// # Example Usecase 124 | /// ```rust 125 | /// use breadcrumbs::{LogListener, Log}; 126 | /// 127 | /// struct MyLogListener; 128 | /// impl LogListener for MyLogListener { 129 | /// fn on_log(&mut self, log: Log) { 130 | /// if !log.level.is_at_least(breadcrumbs::LogLevel::Warn) { 131 | /// log.remove(); 132 | /// } 133 | /// } 134 | /// } 135 | /// ``` 136 | pub fn remove(&self) { 137 | let mut logs = LOGS.lock(); 138 | let index = logs.iter().position(|log| log == self).unwrap(); 139 | logs.remove(index); 140 | } 141 | } 142 | 143 | /// A trait for handling log entries. 144 | pub trait LogListener: Send + Sync { 145 | fn on_log(&mut self, log: Log); 146 | } 147 | 148 | lazy_static! { 149 | static ref LOGS: Arc>> = Arc::new(Mutex::new(Vec::new())); 150 | static ref LOG_LISTENER: Arc>>> = Arc::new(Mutex::new(None)); 151 | } 152 | 153 | /// Initializes the logging system without a listener. 154 | /// Note that the `init!` macro is the preferred method to do this in the public API. 155 | /// ```rust 156 | /// use breadcrumbs::init; 157 | /// init(); 158 | /// ``` 159 | pub fn init() { 160 | LOGS.lock().clear(); 161 | *LOG_LISTENER.lock() = None; 162 | } 163 | 164 | /// Initializes the logging system with a listener. 165 | /// Note that the `init!` macro is the preferred method to do this in the public API. 166 | /// ```rust 167 | /// use breadcrumbs::{init_with_listener, LogListener}; 168 | /// struct MyLogListener; 169 | /// 170 | /// impl LogListener for MyLogListener { 171 | /// fn on_log(&mut self, log: breadcrumbs::Log) { 172 | /// println!("{}", log); 173 | /// } 174 | /// } 175 | /// 176 | /// init_with_listener(Box::new(MyLogListener)); 177 | /// ``` 178 | pub fn init_with_listener(listener: Box) { 179 | LOGS.lock().clear(); 180 | *LOG_LISTENER.lock() = Some(listener); 181 | } 182 | 183 | 184 | /// A macro for initializing the logging system. 185 | /// 186 | /// # Use 187 | /// 188 | /// To initialize the logging system without a listener, do not pass any arguments. 189 | /// 190 | /// To initialize the logging system with a listener, pass a listener implementing `LogListener` as the first argument. 191 | /// 192 | /// # Examples 193 | /// 194 | /// Initialize the logging system without a listener: 195 | /// ``` 196 | /// use breadcrumbs::init; 197 | /// init!(); 198 | /// ``` 199 | /// 200 | /// Initialize the logging system with a listener: 201 | /// ``` 202 | /// use breadcrumbs::{init, LogListener}; 203 | /// struct MyLogListener; 204 | /// 205 | /// impl LogListener for MyLogListener { 206 | /// fn on_log(&mut self, log: breadcrumbs::Log) { 207 | /// println!("{}", log); 208 | /// } 209 | /// } 210 | /// 211 | /// init!(MyLogListener); 212 | #[macro_export] 213 | macro_rules! init { 214 | () => { 215 | $crate::init() 216 | }; 217 | ($arg1:expr) => { 218 | extern crate alloc; 219 | use alloc::boxed::Box; 220 | $crate::init_with_listener(Box::new($arg1)) 221 | }; 222 | } 223 | 224 | /// Logs a message with an optional log level and channel. 225 | /// Note that the `log!` macro is the preferred method to do this in the public API. 226 | /// ```rust 227 | /// use breadcrumbs::{log, LogLevel}; 228 | /// log(Some(LogLevel::Info), Some(String::from("test_channel")), String::from("Test log message")); 229 | /// ``` 230 | pub fn log(level: Option, channel: Option, message: String) { 231 | let log = Log::new(channel.unwrap_or(String::from("")), level.unwrap_or(LogLevel::Info), message.clone()); 232 | LOGS.lock().push(log.clone()); 233 | if let Some(listener) = &mut *LOG_LISTENER.lock() { 234 | listener.on_log(Log::new(log.channel, log.level, log.message)); 235 | } 236 | } 237 | 238 | /// Represents a traceback of logs. 239 | /// `Traceback` beautifully implements `Display` for easy printing. 240 | /// ```rust 241 | /// use breadcrumbs::{Traceback, Log}; 242 | /// let traceback = Traceback(vec![Log::new(String::from("test_channel"), breadcrumbs::LogLevel::Info, String::from("Test log message"))]); 243 | /// assert_eq!(format!("{}", traceback), "[test_channel/Info] Test log message\n"); 244 | /// ``` 245 | pub struct Traceback(pub Vec); 246 | 247 | impl Traceback { 248 | /// Converts the traceback to a beautifully-formatted string. 249 | /// ```rust 250 | /// use breadcrumbs::traceback; 251 | /// let traceback = traceback!(); 252 | /// let traceback_string = traceback.to_string(); 253 | /// ``` 254 | pub fn to_string(&self) -> String { 255 | let mut traceback = String::new(); 256 | for log in &self.0 { 257 | traceback.push_str(&format!("{}\n", log)); 258 | } 259 | traceback 260 | } 261 | } 262 | 263 | impl core::fmt::Display for Traceback { 264 | fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { 265 | write!(f, "{}", self.to_string()) 266 | } 267 | } 268 | 269 | /// Retrieves a traceback of logs based on the minimum log level and channel filter. 270 | /// Note that the `traceback!` macro is the preferred method to do this in the public API. 271 | /// ```rust 272 | /// use breadcrumbs::{get_logs_traceback, LogLevel}; 273 | /// let traceback = get_logs_traceback(Some(LogLevel::Warn), Some(vec![String::from("test_channel")])); 274 | /// ``` 275 | pub fn get_logs_traceback(min_level: Option, channels: Option>) -> Traceback { 276 | let mut logs = Vec::new(); 277 | for log in LOGS.lock().iter() { 278 | if min_level.is_some() && !log.level.is_at_least(min_level.unwrap()) { 279 | continue; 280 | } 281 | if channels.is_some() && !channels.as_ref().unwrap().contains(&log.channel) { 282 | continue; 283 | } 284 | logs.push(log.clone()); 285 | } 286 | Traceback(logs) 287 | } 288 | 289 | /// A macro for generating a `Traceback` of logs, optionally filtered by log level and channel. 290 | /// 291 | /// To only specify a `LogLevel`, use the `traceback_level!` macro. 292 | /// 293 | /// To only specify a `channel`, use the `traceback_channel!` macro. 294 | /// 295 | /// # Examples 296 | /// 297 | /// Traceback with default values: 298 | /// 299 | /// ``` 300 | /// use breadcrumbs::traceback; 301 | /// let traceback = traceback!(); 302 | /// ``` 303 | /// 304 | /// Traceback with a custom log level and channel: 305 | /// 306 | /// ``` 307 | /// use breadcrumbs::{traceback, LogLevel}; 308 | /// let traceback = traceback!(LogLevel::Warn, "test_channel"); 309 | /// ``` 310 | #[macro_export] 311 | macro_rules! traceback { 312 | () => { 313 | $crate::get_logs_traceback(None, None) 314 | }; 315 | ($arg1:expr, $arg2:expr) => { 316 | $crate::get_logs_traceback(Some($arg1), Some(vec![$arg2.to_string()])) 317 | }; 318 | } 319 | 320 | /// A macro for generating a `Traceback` of logs given only a log level. 321 | /// 322 | /// # Examples 323 | /// 324 | /// Basic usage: 325 | /// 326 | /// ``` 327 | /// use breadcrumbs::{traceback_level, LogLevel}; 328 | /// let traceback = traceback_level!(LogLevel::Warn); 329 | /// ``` 330 | #[macro_export] 331 | macro_rules! traceback_level { 332 | ($arg1:expr) => { 333 | $crate::get_logs_traceback(Some($arg1), None) 334 | }; 335 | } 336 | 337 | /// A macro for generating a `Traceback` of logs given only a channel. 338 | /// 339 | /// # Examples 340 | /// 341 | /// Basic usage: 342 | /// 343 | /// ``` 344 | /// use breadcrumbs::traceback_channel; 345 | /// let traceback = traceback_channel!("test_channel"); 346 | /// ``` 347 | #[macro_export] 348 | macro_rules! traceback_channel { 349 | ($arg1:expr) => { 350 | $crate::get_logs_traceback(None, Some(vec![$arg1.to_string()])) 351 | }; 352 | } 353 | 354 | 355 | 356 | /// A macro for logging messages with an optional log level and channel. 357 | /// 358 | /// To only specify a `LogLevel`, use the `log_level!` macro. 359 | /// 360 | /// To only specify a `channel`, use the `log_channel!` macro. 361 | /// 362 | /// # Examples 363 | /// 364 | /// Log with a log level, channel and message 365 | /// ```rust 366 | /// use breadcrumbs::{log, LogLevel}; 367 | /// log!(LogLevel::Info, "test_channel", "Test log message"); 368 | /// ``` 369 | /// 370 | /// Log with just a message 371 | /// 372 | /// ```rust 373 | /// use breadcrumbs::log; 374 | /// log!("Test log message"); 375 | /// ``` 376 | #[macro_export] 377 | macro_rules! log { 378 | ($arg1:expr, $arg2:expr, $arg3:expr) => { 379 | $crate::log(Some($arg1), Some($arg2.to_string()), $arg3.to_string()) 380 | }; 381 | ($arg1:expr) => { 382 | $crate::log(None, None, $arg1.to_string()) 383 | }; 384 | } 385 | 386 | /// A macro for logging messages with a log level only. 387 | /// 388 | /// # Examples 389 | /// 390 | /// ```rust 391 | /// use breadcrumbs::{log_level, LogLevel}; 392 | /// log_level!(LogLevel::Info, "Test log message"); 393 | /// ``` 394 | #[macro_export] 395 | macro_rules! log_level { 396 | ($arg1:expr, $arg2:expr) => { 397 | $crate::log(Some($arg1), None, $arg2.to_string()) 398 | }; 399 | } 400 | 401 | /// A macro for logging messages with a channel only. 402 | /// 403 | /// # Examples 404 | /// 405 | /// ```rust 406 | /// use breadcrumbs::{log_channel, LogLevel}; 407 | /// log_channel!("test_channel", "Test log message"); 408 | /// ``` 409 | #[macro_export] 410 | macro_rules! log_channel { 411 | ($arg1:expr, $arg2:expr) => { 412 | $crate::log(None, Some($arg1.to_string()), $arg2.to_string()) 413 | }; 414 | } 415 | 416 | 417 | 418 | #[cfg(test)] 419 | mod tests { 420 | use super::*; 421 | use alloc::vec; 422 | use crate::alloc::string::ToString; 423 | 424 | // Test the LogLevel enum 425 | #[test] 426 | fn test_log_level_enum() { 427 | assert_eq!(LogLevel::from_str("Verbose"), LogLevel::Verbose); 428 | assert_eq!(LogLevel::from_str("Info"), LogLevel::Info); 429 | assert_eq!(LogLevel::from_str("Warn"), LogLevel::Warn); 430 | assert_eq!(LogLevel::from_str("Error"), LogLevel::Error); 431 | assert_eq!(LogLevel::from_str("Critical"), LogLevel::Critical); 432 | } 433 | 434 | // Test Log and LogListener 435 | struct MockLogListener { 436 | received_log: Option, 437 | } 438 | 439 | impl MockLogListener { 440 | fn new() -> Self { 441 | MockLogListener { received_log: None } 442 | } 443 | } 444 | 445 | impl LogListener for MockLogListener { 446 | fn on_log(&mut self, log: Log) { 447 | self.received_log = Some(log); 448 | } 449 | } 450 | 451 | // Wrapper struct that implements LogListener for Arc> 452 | struct MockLogListenerWrapper(Arc>); 453 | 454 | impl LogListener for MockLogListenerWrapper { 455 | fn on_log(&mut self, log: Log) { 456 | self.0.lock().on_log(log); 457 | } 458 | } 459 | 460 | #[test] 461 | fn test_log_creation_and_handling() { 462 | let mock_listener = Arc::new(Mutex::new(MockLogListener::new())); 463 | let mock_listener_wrapper = MockLogListenerWrapper(mock_listener.clone()); 464 | init!(mock_listener_wrapper); 465 | 466 | log!(LogLevel::Info, "test_channel", "Test log message"); 467 | 468 | let received_log = mock_listener.lock().received_log.clone().expect("Log not received by listener"); 469 | assert_eq!(received_log.level, LogLevel::Info); 470 | assert_eq!(received_log.channel, "test_channel"); 471 | assert_eq!(received_log.message, "Test log message"); 472 | } 473 | 474 | // Test traceback generation 475 | #[test] 476 | fn test_traceback_generation() { 477 | log!(LogLevel::Info, "channel1", "Log 1"); 478 | log!(LogLevel::Warn, "channel2", "Log 2"); 479 | log!(LogLevel::Error, "channel1", "Log 3"); 480 | 481 | let traceback = traceback!(LogLevel::Warn, "channel2").to_string(); 482 | assert!(traceback.contains("[channel2/Warn] Log 2")); 483 | assert!(!traceback.contains("[channel1/Info] Log 1")); 484 | assert!(!traceback.contains("[channel1/Error] Log 3")); 485 | } 486 | 487 | // Test log macros 488 | #[test] 489 | fn test_log_macros() { 490 | log!(LogLevel::Info, "test_channel", "Test log message"); 491 | log_level!(LogLevel::Info, "Test log message"); 492 | log_channel!("test_channel", "Test log message 2"); 493 | 494 | let traceback = traceback!().to_string(); 495 | assert!(traceback.contains("[test_channel/Info] Test log message 2")); 496 | assert!(traceback.contains("[test_channel/Info] Test log message ")); 497 | assert!(traceback.contains("[Info] Test log message")); 498 | } 499 | 500 | // Test the example in the README 501 | #[test] 502 | fn read_me_example() { 503 | init!(); 504 | 505 | log!("Hello, world!"); 506 | log_level!(LogLevel::Info, "Test log message"); 507 | log_channel!("test_channel", "Test log message"); 508 | log!(LogLevel::Info, "test_channel", "Test log message"); 509 | } 510 | 511 | struct MyLogListener2 { 512 | success: bool, 513 | } 514 | 515 | impl LogListener for MyLogListener2 { 516 | fn on_log(&mut self, log: Log) { 517 | if log.level.is_at_least(LogLevel::Warn) { 518 | self.success = true; 519 | } 520 | } 521 | } 522 | 523 | struct MockLogListenerWrapper2(Arc>); 524 | 525 | impl LogListener for MockLogListenerWrapper2 { 526 | fn on_log(&mut self, log: Log) { 527 | self.0.lock().on_log(log); 528 | } 529 | } 530 | 531 | #[test] 532 | fn no_std_readme_example() { 533 | let log_handler = Arc::new(Mutex::new(MyLogListener2 { success: false })); 534 | let log_handler_wrapper = MockLogListenerWrapper2(log_handler.clone()); 535 | 536 | init!(log_handler_wrapper); 537 | 538 | log!(LogLevel::Error, "test_channel", "Test log message"); 539 | 540 | assert!(log_handler.lock().success); 541 | } 542 | } 543 | 544 | --------------------------------------------------------------------------------