├── .github └── FUNDING.yml ├── .gitignore ├── Cargo.lock ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md └── src └── lib.rs /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: [fasterthanlime] 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | -------------------------------------------------------------------------------- /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 = "soprintln" 7 | version = "3.2.0" 8 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "soprintln" 3 | version = "3.2.1" 4 | edition = "2021" 5 | authors = ["Amos Wenger "] 6 | license = "MIT OR Apache-2.0" 7 | readme = "README.md" 8 | repository = "https://github.com/bearcove/soprintln" 9 | description = "println wrapper that includes a timestamp, shared object ID and thread ID with useful colors" 10 | categories = ["development-tools::debugging", "command-line-utilities"] 11 | keywords = ["logging", "debugging", "console", "println"] 12 | 13 | [dependencies] 14 | 15 | [features] 16 | print = [] 17 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | https://www.apache.org/licenses/LICENSE-2.0 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 | https://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. -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Permission is hereby granted, free of charge, to any person obtaining a copy 2 | of this software and associated documentation files (the "Software"), to deal 3 | in the Software without restriction, including without limitation the rights 4 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 5 | copies of the Software, and to permit persons to whom the Software is 6 | furnished to do so, subject to the following conditions: 7 | 8 | The above copyright notice and this permission notice shall be included in all 9 | copies or substantial portions of the Software. 10 | 11 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 12 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 13 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 14 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 15 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 16 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 17 | SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![license: MIT/Apache-2.0](https://img.shields.io/badge/license-MIT%2FApache--2.0-blue.svg)](LICENSE-MIT) 2 | [![crates.io](https://img.shields.io/crates/v/soprintln.svg)](https://crates.io/crates/soprintln) 3 | [![docs.rs](https://docs.rs/soprintln/badge.svg)](https://docs.rs/soprintln) 4 | 5 | # soprintln 6 | 7 | (Note: This is only useful when implementing the `xgraph` dynamic linking model, 8 | see ) 9 | 10 | ![](https://github.com/user-attachments/assets/3bc0e0e1-cade-4b27-88b5-5d73029a0e74) 11 | 12 | This crate provides the `soprintln!` macro, a debug variant of `println!` that: 13 | 14 | * Is disabled if the `print` feature cargo feature is not enabled 15 | * Is disabled if the `SOPRINTLN` environment variable isn't set to one 16 | * Prefixes the message with: 17 | * a truncated millisecond timestamp 18 | * a beacon of the shared object ID 19 | * a beacon of the thread name + ID 20 | 21 | Beacons are 64-bit integers (can be initialized from pointers) whose color 22 | depend on their value. It makes it easier to spot the same value being re-used 23 | a bunch. 24 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | // Note: there's one copy of this static per shared object on purpose — that's the one 2 | // static we DON'T want to deduplicate. 3 | #[used] 4 | static SHARED_OBJECT_ID_REF: u64 = 0; 5 | 6 | /// Returns a unique identifier for the current shared object. 7 | pub fn shared_object_id() -> u64 { 8 | &SHARED_OBJECT_ID_REF as *const _ as u64 9 | } 10 | 11 | /// The name of this package 12 | pub static mut SO_NAME: &str = ""; 13 | 14 | /// Initializes the `SO_NAME` static to make logs more readable. 15 | #[macro_export] 16 | macro_rules! init { 17 | () => { 18 | static INIT: std::sync::Once = std::sync::Once::new(); 19 | INIT.call_once(|| unsafe { 20 | $crate::SO_NAME = Box::leak(Box::new(format!("{: <12}", env!("CARGO_PKG_NAME")))); 21 | }); 22 | }; 23 | } 24 | 25 | /// Prints a message, prefixed with a cycling millisecond timestamp (wraps at 99999), 26 | /// a colorized shared object id, a colorized thread name+id, and the given message. 27 | #[macro_export] 28 | #[cfg(feature = "print")] 29 | macro_rules! soprintln { 30 | ($($arg:tt)*) => { 31 | { 32 | use std::sync::atomic::{AtomicBool, Ordering}; 33 | static ENV_CHECKED: std::sync::Once = std::sync::Once::new(); 34 | static SHOULD_PRINT: AtomicBool = AtomicBool::new(false); 35 | ENV_CHECKED.call_once(|| { 36 | let should_print = std::env::var("SOPRINTLN").map(|v| v == "1").unwrap_or(false); 37 | SHOULD_PRINT.store(should_print, Ordering::Relaxed); 38 | }); 39 | 40 | if SHOULD_PRINT.load(Ordering::Relaxed) { 41 | // this formatting is terribly wasteful — PRs welcome 42 | 43 | let so_id = $crate::shared_object_id(); 44 | let so_mode_and_id = $crate::Beacon::new(unsafe { $crate::SO_NAME }, so_id).show_val(false); 45 | let curr_thread = std::thread::current(); 46 | let tid = format!("{:?}", curr_thread.id()); 47 | // strip `ThreadId(` prefix 48 | let tid = tid.strip_prefix("ThreadId(").unwrap_or(&tid); 49 | // strip `)` suffix 50 | let tid = tid.strip_suffix(")").unwrap_or(&tid); 51 | // parse tid as u64 52 | let tid = tid.parse::().unwrap_or(0); 53 | 54 | let thread_name = curr_thread.name().unwrap_or("").trim(); 55 | let thread_name = if thread_name.len() > 20 { 56 | format!("{}...{}", &thread_name[..8], &thread_name[thread_name.len() - 9..]) 57 | } else { 58 | format!("{: <20}", thread_name) 59 | }; 60 | let thread = $crate::Beacon::new(&thread_name, tid); 61 | 62 | let timestamp = ::std::time::SystemTime::now().duration_since(::std::time::UNIX_EPOCH).unwrap().as_millis() % 99999; 63 | 64 | // compute the 24-bit ANSI color of the timestamp based on its value between 0 and 99999 65 | let hue = (timestamp % 1000) as f64 / 999.0 * 360.0; 66 | let saturation = 40.0; 67 | let lightness = 100.0; 68 | let (fg_r, fg_g, fg_b) = $crate::hsl_to_rgb(hue, saturation, lightness); 69 | let (bg_r, bg_g, bg_b) = $crate::hsl_to_rgb(hue, saturation * 0.8, lightness * 0.5); 70 | 71 | // coloring the timestamp helps spot time gaps in the log 72 | 73 | // FIXME: this is probably not necessary, but without it, rustc complains about 74 | // capturing variables in format_args? 75 | let msg = format!($($arg)*); 76 | eprintln!("⏰\x1b[48;2;{};{};{}m\x1b[38;2;{};{};{}m{:05}\x1b[0m 📦{so_mode_and_id} 🧵{thread} {msg}", bg_r, bg_g, bg_b, fg_r, fg_g, fg_b, timestamp); 77 | } 78 | } 79 | }; 80 | } 81 | 82 | /// `soprintln!` prints a message prefixed by a truncated timestamp, shared object ID and thread ID. 83 | /// 84 | /// It is costly, which is why it's behind a cargo feature AND an environment variable. 85 | /// 86 | /// To see soprintln output, enable the `soprintln` cargo feature, and set the `SOPRINTLN` 87 | /// environment variable to `1`. 88 | #[macro_export] 89 | #[cfg(not(feature = "print"))] 90 | macro_rules! soprintln { 91 | ($($arg:tt)*) => { 92 | let _ = ($($arg)*); 93 | }; 94 | } 95 | 96 | /// A `u64` whose 24-bit ANSI color is determined by its value. 97 | /// 98 | /// Used by the [`soprintln`] macro to visually distinguish shared objects and threads. 99 | pub struct Beacon<'a> { 100 | fg: (u8, u8, u8), 101 | bg: (u8, u8, u8), 102 | name: &'a str, 103 | val: u64, 104 | show_val: bool, 105 | } 106 | 107 | impl<'a> Beacon<'a> { 108 | /// Creates a new `Beacon` from a pointer. 109 | pub fn from_ptr(name: &'a str, ptr: *const T) -> Self { 110 | Self::new(name, ptr as u64) 111 | } 112 | 113 | /// Creates a new `Beacon` from a reference. 114 | pub fn from_ref(name: &'a str, r: &T) -> Self { 115 | Self::new(name, r as *const T as u64) 116 | } 117 | 118 | /// Creates a new `Beacon` with the given extra string and value. 119 | pub fn new(name: &'a str, u: u64) -> Self { 120 | use std::collections::hash_map::DefaultHasher; 121 | use std::hash::{Hash, Hasher}; 122 | 123 | fn hash(x: u64) -> u64 { 124 | let mut hasher = DefaultHasher::new(); 125 | x.hash(&mut hasher); 126 | hasher.finish() 127 | } 128 | 129 | let hashed_float = (hash(u) as f64) / (u64::MAX as f64); 130 | let h = hashed_float * 360.0; 131 | let s = 37.0; 132 | let l = 91.0; 133 | 134 | let fg = hsl_to_rgb(h, s, l); 135 | let bg = hsl_to_rgb(h, s * 0.8, l * 0.6); 136 | 137 | Self { 138 | fg, 139 | bg, 140 | name, 141 | val: u, 142 | show_val: true, 143 | } 144 | } 145 | 146 | pub fn show_val(mut self, show_val: bool) -> Self { 147 | self.show_val = show_val; 148 | self 149 | } 150 | } 151 | 152 | /// Converts a hue, saturation, and lightness to an RGB color. 153 | /// 154 | /// h is in [0, 360) 155 | /// s is in [0, 100] 156 | /// l is in [0, 100] 157 | pub fn hsl_to_rgb(h: f64, s: f64, l: f64) -> (u8, u8, u8) { 158 | let h = h / 360.0; 159 | let s = s / 100.0; 160 | let l = l / 100.0; 161 | 162 | let c = (1.0 - (2.0 * l - 1.0).abs()) * s; 163 | let x = c * (1.0 - ((h * 6.0) % 2.0 - 1.0).abs()); 164 | let m = l - c / 2.0; 165 | 166 | let (r, g, b) = match (h * 6.0) as u8 { 167 | 0 | 6 => (c, x, 0.0), 168 | 1 => (x, c, 0.0), 169 | 2 => (0.0, c, x), 170 | 3 => (0.0, x, c), 171 | 4 => (x, 0.0, c), 172 | _ => (c, 0.0, x), 173 | }; 174 | 175 | ( 176 | ((r + m) * 255.0) as u8, 177 | ((g + m) * 255.0) as u8, 178 | ((b + m) * 255.0) as u8, 179 | ) 180 | } 181 | 182 | impl<'a> std::fmt::Display for Beacon<'a> { 183 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 184 | if self.show_val { 185 | write!( 186 | f, 187 | "\x1b[48;2;{};{};{}m\x1b[38;2;{};{};{}m{}·{:03x}\x1b[0m", 188 | self.bg.0, 189 | self.bg.1, 190 | self.bg.2, 191 | self.fg.0, 192 | self.fg.1, 193 | self.fg.2, 194 | self.name, 195 | self.val 196 | ) 197 | } else { 198 | write!( 199 | f, 200 | "\x1b[48;2;{};{};{}m\x1b[38;2;{};{};{}m{}\x1b[0m", 201 | self.bg.0, self.bg.1, self.bg.2, self.fg.0, self.fg.1, self.fg.2, self.name 202 | ) 203 | } 204 | } 205 | } 206 | 207 | #[cfg(test)] 208 | mod tests { 209 | use super::*; 210 | 211 | #[test] 212 | fn test_beacon() { 213 | crate::init!(); 214 | for i in 0..128 { 215 | if i == 64 { 216 | std::thread::sleep(std::time::Duration::from_millis(100)); 217 | } 218 | 219 | std::thread::sleep(std::time::Duration::from_millis(1)); 220 | let b = Beacon::new("test", 0x12345678 + i); 221 | soprintln!("{b}"); 222 | } 223 | } 224 | 225 | #[test] 226 | fn test_soprintln() { 227 | crate::init!(); 228 | soprintln!("test"); 229 | } 230 | } 231 | --------------------------------------------------------------------------------