├── .gitignore
├── CONTRIBUTING.md
├── Cargo.toml
├── LICENSE-APACHE
├── LICENSE-MIT
├── README.md
├── examples
├── custom-format.rs
├── custom-theme.rs
├── default.rs
├── inline-gradient.rs
├── json.rs
├── multi-line-gradient.rs
├── multi-threaded.rs
└── util.rs
├── images
├── inline-gradient-color.png
├── multi-line-gradient.png
├── simple-theme.svg
├── solid-color.png
├── spectral-theme.svg
├── swing.gif
└── swing.svg
└── src
├── color.rs
├── config.rs
├── lib.rs
├── paint.rs
├── sculpt.rs
├── theme.rs
└── write.rs
/.gitignore:
--------------------------------------------------------------------------------
1 | # Generated by Cargo
2 | # will have compiled files and executables
3 | /target/
4 |
5 | # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
6 | # More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html
7 | Cargo.lock
8 |
9 | # These are backup files generated by rustfmt
10 | **/*.rs.bk
11 |
12 | # IDEs
13 | .idea/
14 | *.swp
15 |
16 |
17 | # Added by cargo
18 |
19 | /target
20 |
21 |
22 | # Added by cargo
23 | #
24 | # already existing elements were commented out
25 |
26 | #/target
27 | #Cargo.lock
28 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing
2 |
3 | Thank you for making/considering a contribution to this project! These guidelines are not rules, but are designed to help us keep this project easily maintainable and consistent.
4 |
5 | ## Commit messages
6 |
7 | Ideal commit messages give a high level description of your change, and are written in [the imperative mood](https://en.wikipedia.org/wiki/Imperative_mood). For example:
8 |
9 | ```shell
10 | # this is in the imperative mood
11 | $ git commit -m 'Add a cool new feature'
12 |
13 | # this is not
14 | $ git commit -m 'Added a cool new feature'
15 |
16 | # this is also not
17 | $ git commit -m 'Cool new feature'
18 | ```
19 |
20 | Commit messages written this way make it easy to look at the `git log` and quickly grasp major actions/changes that take us from one commit to another.
21 |
22 | ## Styling and testing
23 |
24 | Before making a pull request, please format your changes and make sure all tests still pass:
25 |
26 | ```shell
27 | $ cargo fmt
28 | $ cargo test
29 | ```
--------------------------------------------------------------------------------
/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "swing"
3 | version = "0.1.0"
4 | authors = ["Diffuse <48339639+diffuse@users.noreply.github.com>"]
5 | edition = "2018"
6 | readme = "README.md"
7 | repository = "https://github.com/diffuse/swing"
8 | license = "MIT/Apache-2.0"
9 | description = "Log like it's 1978 with this logging implementation for the log crate"
10 | keywords = ["log", "logging", "swing", "color"]
11 | categories = ["development-tools::debugging"]
12 |
13 | [dependencies]
14 | log = { version = "0.4", features = ["std", "serde"] }
15 | serde_json = { version = "1.0", features = ["preserve_order"]}
16 | time = { version = "0.3.11", features = ["formatting"] }
17 | colored = "2"
18 | unicode-segmentation = "1.9.0"
19 |
20 | [dev-dependencies]
21 | lipsum = "0.8"
22 | num = "0.4"
23 | rand = "0.8"
24 |
--------------------------------------------------------------------------------
/LICENSE-APACHE:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | https://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
179 | Copyright 2022 diffuse
180 |
181 | Licensed under the Apache License, Version 2.0 (the "License");
182 | you may not use this file except in compliance with the License.
183 | You may obtain a copy of the License at
184 |
185 | https://www.apache.org/licenses/LICENSE-2.0
186 |
187 | Unless required by applicable law or agreed to in writing, software
188 | distributed under the License is distributed on an "AS IS" BASIS,
189 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
190 | See the License for the specific language governing permissions and
191 | limitations under the License.
192 |
--------------------------------------------------------------------------------
/LICENSE-MIT:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2022 diffuse
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | # swing
4 |
5 | Log like it's 1978 with this logging implementation for the [log](https://crates.io/crates/log) crate. Color themes, pluggable formatting, we've got it all!
6 |
7 | 
8 |
9 | # Installation
10 |
11 | Add the following to `Cargo.toml`:
12 |
13 | ```toml
14 | [dependencies]
15 | swing = "0.1"
16 | log = "0.4"
17 | ```
18 |
19 | # Quick start
20 |
21 | Create and initialize a `Logger`, then use the [log](https://crates.io/crates/log) crate macros to log messages:
22 |
23 | ```rust
24 | use swing::Logger;
25 |
26 | fn main() {
27 | // setup logger
28 | Logger::new().init().unwrap();
29 |
30 | // log away!
31 | log::trace!("foo");
32 | log::debug!("bar");
33 | log::info!("baz");
34 | log::warn!("spam");
35 | log::error!("eggs");
36 | }
37 | ```
38 |
39 | Note that the default `Logger` created with `::new()` has a log level filter of `info`, so in this example, only `"baz"` `"spam"` and `"eggs"` will be printed to the console.
40 |
41 | # Logger config options
42 |
43 | For more control, `Logger`s can be created with a `Config` struct via `Logger::with_config`:
44 |
45 | ```rust
46 | use swing::{Config, Logger};
47 | use log::LevelFilter;
48 |
49 | fn main() {
50 | let config = Config {
51 | level: LevelFilter::Trace,
52 | ..Default::default()
53 | };
54 |
55 | Logger::with_config(config).init().unwrap();
56 | }
57 | ```
58 |
59 | The default configuration uses the following settings:
60 |
61 | ```rust
62 | use swing::{Config, ColorFormat, RecordFormat, theme};
63 | use log::LevelFilter;
64 |
65 | Config {
66 | level: LevelFilter::Info,
67 | record_format: RecordFormat::Simple,
68 | color_format: Some(ColorFormat::Solid),
69 | theme: Box::new(theme::Spectral {}),
70 | use_stderr: true,
71 | };
72 | ```
73 |
74 | Each setting is explained in its own subsection:
75 |
76 | - [level](#level)
77 | - [record_format](#record_format)
78 | - [color_format](#color_format)
79 | - [theme](#theme)
80 | - [use_stderr](#use_stderr)
81 |
82 | ## level
83 |
84 | The `level` setting controls which log records are processed and which are ignored. The `LevelFilter` enum used in `Config` is taken directly
85 | from [the log crate](https://docs.rs/log/latest/log/enum.LevelFilter.html). It defines the following variants:
86 |
87 | - `Off`
88 | - `Trace`
89 | - `Debug`
90 | - `Info`
91 | - `Warn`
92 | - `Error`
93 |
94 | Only records logged at or above the chosen severity will be output to `stdout`/`stderr`. For example:
95 |
96 | ```rust
97 | use swing::Config;
98 | use log::LevelFilter;
99 |
100 | // --snip--
101 |
102 | let config = Config {
103 | level: LevelFilter::Info,
104 | ..Default::default()
105 | };
106 |
107 | // --snip--
108 |
109 | // trace and debug logs will be ignored, only info, warn, and error messages will print to the screen
110 | log::trace!("foo");
111 | log::debug!("bar");
112 | log::info!("baz");
113 | log::warn!("spam");
114 | log::error!("eggs");
115 | ```
116 |
117 | ## record_format
118 |
119 | The `record_format` setting controls how log records are (structurally) formatted when they are displayed. Each call to the [log](https://docs.rs/log/latest/log/)
120 | crate macros (`trace!`, `info!`, etc...) generates a log [record](https://docs.rs/log/latest/log/struct.Record.html). These records are then formatted by this crate using one
121 | of the variants in the `RecordFormat` enum:
122 |
123 | - `Json`
124 | - `Simple`
125 | - `Custom`
126 |
127 | Record formats are imported and used by:
128 |
129 | ```rust
130 | use swing::{Config, Logger, RecordFormat};
131 | use log::LevelFilter;
132 |
133 | fn main() {
134 | let config = Config {
135 | level: LevelFilter::Trace,
136 | record_format: RecordFormat::Simple,
137 | ..Default::default()
138 | };
139 | Logger::with_config(config).init().unwrap();
140 | }
141 | ```
142 |
143 | ### Simple format
144 |
145 | This is the default record format and will generate log lines that look like this:
146 |
147 | ```text
148 | 2022-07-31T20:25:31.108560826Z [main] TRACE - foo
149 | 2022-07-31T20:25:31.108623041Z [main] DEBUG - bar
150 | 2022-07-31T20:25:31.108645580Z [main] INFO - baz
151 | 2022-07-31T20:25:31.108667634Z [main] WARN - spam
152 | 2022-07-31T20:25:31.108736790Z [main] ERROR - eggs
153 | ```
154 |
155 | Note that times are always in ISO 8601 format, UTC time.
156 |
157 | ### Json format
158 |
159 | This record format will generate log lines as JSON:
160 |
161 | ```json
162 | {"time":"2022-07-31T20:28:11.863634602Z","level":"TRACE","target":"main","message":"foo"}
163 | {"time":"2022-07-31T20:28:11.864114090Z","level":"DEBUG","target":"main","message":"bar"}
164 | {"time":"2022-07-31T20:28:11.864201937Z","level":"INFO","target":"main","message":"baz"}
165 | {"time":"2022-07-31T20:28:11.864269093Z","level":"WARN","target":"main","message":"spam"}
166 | {"time":"2022-07-31T20:28:11.864372619Z","level":"ERROR","target":"main","message":"eggs"}
167 | ```
168 |
169 | Note that times are always in ISO 8601 format, UTC time.
170 |
171 | ### Custom format
172 |
173 | If you don't like any of the above formats, you can inject your own custom record formatting by using the `Custom` format:
174 |
175 | ```rust
176 | use swing::{Config, Logger, RecordFormat};
177 | use log::{LevelFilter, Record};
178 |
179 | fn main() {
180 | let fmt_rec = Box::new(|r: &Record| -> String {
181 | format!("{} - {}", r.level(), r.args())
182 | });
183 |
184 | let config = Config {
185 | level: LevelFilter::Trace,
186 | record_format: RecordFormat::Custom(fmt_rec),
187 | ..Default::default()
188 | };
189 | Logger::with_config(config).init().unwrap();
190 |
191 | // log away!
192 | log::trace!("foo");
193 | log::debug!("bar");
194 | log::info!("baz");
195 | log::warn!("spam");
196 | log::error!("eggs");
197 | }
198 | ```
199 |
200 | The above example format will generate log lines that look like this:
201 |
202 | ```text
203 | TRACE - foo
204 | DEBUG - bar
205 | INFO - baz
206 | WARN - spam
207 | ERROR - eggs
208 | ```
209 |
210 | See [the log crate "Record" struct](https://docs.rs/log/latest/log/struct.Record.html) for available record fields/methods to use within the custom format closure.
211 |
212 | For reference, the `Simple` record format can be reproduced with the following `Custom` record format:
213 |
214 | ```rust
215 | use time::format_description::well_known::Iso8601;
216 | use time::OffsetDateTime;
217 | use log::Record;
218 |
219 | // --snip--
220 |
221 | let fmt_rec = Box::new(|r: &Record| -> String {
222 | let now = OffsetDateTime::now_utc()
223 | .format(&Iso8601::DEFAULT)
224 | .expect("Failed to format time as ISO 8601");
225 |
226 | format!("{} [{}] {} - {}", now, r.target(), r.level(), r.args())
227 | });
228 | ```
229 |
230 | ## color_format
231 |
232 | The `color_format` setting controls how log records are colored (specifically how a theme is applied) when they are displayed. Log records are formatted by this crate using one of the variants in the `ColorFormat` enum, or `None`:
233 |
234 | - `Solid`
235 | - `InlineGradient()`
236 | - `MultiLineGradient()`
237 |
238 | Color formats are imported and used by:
239 |
240 | ```rust
241 | use swing::{Config, Logger, ColorFormat};
242 | use log::LevelFilter;
243 |
244 | fn main() {
245 | let config = Config {
246 | level: LevelFilter::Trace,
247 | color_format: Some(ColorFormat::Solid),
248 | ..Default::default()
249 | };
250 | Logger::with_config(config).init().unwrap();
251 | }
252 | ```
253 |
254 | ### None format
255 |
256 | If `None` is provided as the `color_format`, log records will not be colored (warnings and errors will still be made bold).
257 |
258 | ### Solid format
259 |
260 | This will generate log lines that each have a solid color, determined by log level. The below screenshot uses the `Spectral` theme and the following color format:
261 | ```rust
262 | use swing::ColorFormat;
263 |
264 | // --snip--
265 |
266 | let color_format = Some(ColorFormat::Solid);
267 | ```
268 | 
269 |
270 | ### Inline gradient format
271 |
272 | This will generate log lines that are colored with a repeating linear gradient from left to right, determined by log level. The below screenshot uses the `Spectral` theme and the following color format:
273 | ```rust
274 | use swing::ColorFormat;
275 |
276 | // --snip--
277 |
278 | let color_format = Some(ColorFormat::InlineGradient(60));
279 | ```
280 | 
281 |
282 | This color format takes a `usize` argument which represents the number of steps required to go from the start color to the end color for each level's color gradient. Gradients will be traversed in alternating ascending and descending order. In the above example, it will take `60` characters to go from the starting color for each line to the ending color, then `60` more characters to return to the starting color again.
283 |
284 | Note that this color format will incur a nontrivial performance hit with heavy logging. If you have a lot of logs and are trying to break the next land speed record for fastest program, you probably shouldn't use this color format.
285 |
286 | ### Multi-line gradient format
287 |
288 | This will generate log lines that each have a solid color, determined by level. Lines within each level will change color step by step, moving through a linear gradient of colors determined by the relevant log level. The below screenshot uses the `Spectral` theme and the following color format:
289 | ```rust
290 | use swing::ColorFormat;
291 |
292 | // --snip--
293 |
294 | let color_format = Some(ColorFormat::MultiLineGradient(30));
295 | ```
296 | 
297 |
298 | This color format takes a `usize` argument which represents the number of steps required to go from the start color to the end color for each level's color gradient. Gradients will be traversed in alternating ascending and descending order. In the above example, it will take `30` lines to go from the starting color for each level to the ending color, then `30` more lines to return to the starting color again.
299 |
300 | ## theme
301 |
302 | The `theme` setting determines the color palette to use when applying color formats. It is set by providing an instance of something that implements the `Theme` trait:
303 | ```rust
304 | use swing::theme::Spectral;
305 |
306 | // --snip--
307 |
308 | let theme = Box::new(Spectral {});
309 | ```
310 |
311 | This crate provides a few premade themes, but you can also implement your own, or use themes made by others.
312 |
313 | ### Spectral
314 |
315 | The `Spectral` theme provides a palette that moves through the color spectrum in 5 segments:
316 |
317 | 
318 |
319 | ### Simple
320 |
321 | The `Simple` theme provides a relatively flat palette that uses dark/light versions of 5 main colors:
322 |
323 | 
324 |
325 | ### Creating your own custom theme
326 |
327 | Anything that implements the `Theme` trait can be used as a theme. To make your own theme, you just have to implement this trait for a struct, then set `Config`'s `theme` member to a boxed instance of that struct. See `examples/custom-theme.rs` for an example of a custom theme implementation.
328 |
329 | ## use_stderr
330 |
331 | The `use_stderr` setting determines if log records are split between `stdout` and `stderr` or not. When this field is false, all log records will be written to `stdout`. When this field is true, records at levels `trace`, `debug`, and `info` are written to `stdout`, while those at `warn` and `error` levels are written to `stderr`.
332 |
333 | # Examples
334 |
335 | See the `examples` directory for a variety of usage examples. You can run any of these examples with:
336 | ```shell
337 | $ cargo run --example
338 | ```
339 |
340 | # Stream redirection tips in Linux
341 |
342 | When logging with `use_stderr` set to true, you must redirect both streams to capture all output.
343 |
344 | To redirect all log records to file:
345 |
346 | ```shell
347 | $ ./example &> foo.log
348 | ```
349 |
350 | To redirect all logs to file, while watching output:
351 |
352 | ```shell
353 | # write all log data to foo.log and stdout simultaneously
354 | $ ./example 2>&1 | tee foo.log
355 | ```
356 |
357 | You can add `jq` for pretty printing when using `RecordFormat::Json`:
358 |
359 | ```shell
360 | $ ./example 2>&1 | tee foo.log | jq
361 | ```
362 |
363 | # Contributing
364 |
365 | Contributions are welcome and greatly appreciated. See [CONTRIBUTING](CONTRIBUTING.md) for some general guidelines.
366 |
367 | # License
368 |
369 | Licensed under either of [Apache License, Version 2.0](https://github.com/diffuse/swing/blob/main/LICENSE-APACHE) or [MIT license](https://github.com/diffuse/swing/blob/main/LICENSE-MIT) at your option.
370 |
371 | Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in swing by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.
--------------------------------------------------------------------------------
/examples/custom-format.rs:
--------------------------------------------------------------------------------
1 | use log::{LevelFilter, Record};
2 | use swing::{Config, Logger, RecordFormat};
3 |
4 | fn main() {
5 | // create your own conversion from a
6 | // log::Record to a String and wrap it
7 | // in a Box to use with a Logger
8 | let fmt_rec = Box::new(|r: &Record| -> String {
9 | format!("[{}] {} - {}", r.target(), r.level(), r.args())
10 | });
11 |
12 | // setup logger
13 | let config = Config {
14 | level: LevelFilter::Trace,
15 | record_format: RecordFormat::Custom(fmt_rec),
16 | ..Default::default()
17 | };
18 | Logger::with_config(config).init().unwrap();
19 |
20 | // log away!
21 | log::trace!("foo");
22 | log::debug!("bar");
23 | log::info!("baz");
24 | log::warn!("spam");
25 | log::error!("eggs");
26 | }
27 |
--------------------------------------------------------------------------------
/examples/custom-theme.rs:
--------------------------------------------------------------------------------
1 | use log::{Level, LevelFilter};
2 | use swing::{Color, ColorFormat, Config, Logger, Rgb, RgbRange, Theme};
3 |
4 | /// Custom theme
5 | pub struct MyTheme {}
6 |
7 | impl Theme for MyTheme {
8 | /// This method returns the color that will be used for each
9 | /// level when the Solid color format is chosen
10 | ///
11 | /// This implementation simply uses the start color
12 | /// from each level's color range as its solid color, but you
13 | /// can perform another level match here and choose whichever
14 | /// specific colors you would like.
15 | fn solid(&self, level: Level) -> Rgb {
16 | self.range(level).start
17 | }
18 |
19 | /// This method returns a range of color that each log level will
20 | /// use. The provided color range defines the bounds for linear gradients,
21 | /// and can be used to calculate solid colors, if desired.
22 | fn range(&self, level: Level) -> RgbRange {
23 | match level {
24 | Level::Trace => RgbRange {
25 | start: Rgb {
26 | r: 245,
27 | g: 1,
28 | b: 167,
29 | },
30 | end: Rgb {
31 | r: 245,
32 | g: 121,
33 | b: 167,
34 | },
35 | },
36 | Level::Debug => RgbRange {
37 | start: Color::Cyan.value(),
38 | end: Rgb {
39 | r: 162,
40 | g: 187,
41 | b: 214,
42 | },
43 | },
44 | Level::Info => RgbRange {
45 | start: Color::Green.value(),
46 | end: Rgb {
47 | r: 209,
48 | g: 235,
49 | b: 165,
50 | },
51 | },
52 | Level::Warn => RgbRange {
53 | start: Color::Yellow.value(),
54 | end: Rgb {
55 | r: 214,
56 | g: 202,
57 | b: 169,
58 | },
59 | },
60 | Level::Error => RgbRange {
61 | start: Color::Red.value(),
62 | end: Rgb {
63 | r: 245,
64 | g: 171,
65 | b: 171,
66 | },
67 | },
68 | }
69 | }
70 | }
71 |
72 | fn main() {
73 | // setup logger
74 | let config = Config {
75 | level: LevelFilter::Trace,
76 | theme: Box::new(MyTheme {}),
77 | color_format: Some(ColorFormat::InlineGradient(20)),
78 | ..Default::default()
79 | };
80 | Logger::with_config(config).init().unwrap();
81 |
82 | // log away!
83 | log::trace!("I looked forward to making a crate");
84 | log::debug!("Where colors in logs annotate,");
85 | log::info!("But encountered a yak");
86 | log::warn!("And couldn't look back");
87 | log::error!("'til the hair on that yak did abate");
88 | }
89 |
--------------------------------------------------------------------------------
/examples/default.rs:
--------------------------------------------------------------------------------
1 | use swing::Logger;
2 |
3 | fn main() {
4 | // setup logger
5 | Logger::new().init().unwrap();
6 |
7 | // log away!
8 | log::trace!("foo");
9 | log::debug!("bar");
10 | log::info!("baz");
11 | log::warn!("spam");
12 | log::error!("eggs");
13 | }
14 |
--------------------------------------------------------------------------------
/examples/inline-gradient.rs:
--------------------------------------------------------------------------------
1 | use log::LevelFilter;
2 | use swing::{theme::Spectral, ColorFormat, Config, Logger, RecordFormat};
3 | mod util;
4 |
5 | fn main() {
6 | // setup logger
7 | let config = Config {
8 | level: LevelFilter::Trace,
9 | record_format: RecordFormat::Simple,
10 | color_format: Some(ColorFormat::InlineGradient(200)),
11 | theme: Box::new(Spectral {}),
12 | ..Default::default()
13 | };
14 | Logger::with_config(config).init().unwrap();
15 |
16 | util::log_sample_messages(100);
17 | }
18 |
--------------------------------------------------------------------------------
/examples/json.rs:
--------------------------------------------------------------------------------
1 | use log::LevelFilter;
2 | use swing::{Config, Logger, RecordFormat};
3 |
4 | fn main() {
5 | // setup logger
6 | let config = Config {
7 | level: LevelFilter::Trace,
8 | record_format: RecordFormat::Json,
9 | ..Default::default()
10 | };
11 | Logger::with_config(config).init().unwrap();
12 |
13 | // log away!
14 | log::trace!("foo");
15 | log::debug!("bar");
16 | log::info!("baz");
17 | log::warn!("spam");
18 | log::error!("eggs");
19 | }
20 |
--------------------------------------------------------------------------------
/examples/multi-line-gradient.rs:
--------------------------------------------------------------------------------
1 | use log::LevelFilter;
2 | use swing::{theme::Spectral, ColorFormat, Config, Logger, RecordFormat};
3 | mod util;
4 |
5 | fn main() {
6 | // setup logger
7 | let config = Config {
8 | level: LevelFilter::Trace,
9 | record_format: RecordFormat::Simple,
10 | color_format: Some(ColorFormat::MultiLineGradient(20)),
11 | theme: Box::new(Spectral {}),
12 | ..Default::default()
13 | };
14 | Logger::with_config(config).init().unwrap();
15 |
16 | util::log_sample_messages(1000);
17 | }
18 |
--------------------------------------------------------------------------------
/examples/multi-threaded.rs:
--------------------------------------------------------------------------------
1 | use log::LevelFilter;
2 | use std::thread;
3 | use swing::{theme::Spectral, ColorFormat, Config, Logger};
4 | mod util;
5 |
6 | fn main() {
7 | // setup logger
8 | let config = Config {
9 | level: LevelFilter::Trace,
10 | color_format: Some(ColorFormat::MultiLineGradient(20)),
11 | theme: Box::new(Spectral {}),
12 | ..Default::default()
13 | };
14 | Logger::with_config(config).init().unwrap();
15 |
16 | // log sample messages from 10 threads simultaneously
17 | let mut handles = vec![];
18 |
19 | for _ in 0..10 {
20 | handles.push(thread::spawn(move || {
21 | util::log_sample_messages(1000);
22 | }));
23 | }
24 |
25 | for handle in handles {
26 | handle.join().unwrap();
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/examples/util.rs:
--------------------------------------------------------------------------------
1 | use lipsum::lipsum;
2 | use rand::Rng;
3 |
4 | /// log n sample messages, weighted towards the default _ match arm
5 | pub fn log_sample_messages(n: usize) {
6 | for _ in 0..n {
7 | let n = rand::thread_rng().gen_range(0..20);
8 | let msg = lipsum(n);
9 |
10 | match rand::thread_rng().gen_range(0..15) {
11 | 0 => log::trace!("{}", msg),
12 | 1 => log::debug!("{}", msg),
13 | 2 => log::info!("{}", msg),
14 | 3 => log::warn!("{}", msg),
15 | 4 => log::error!("{}", msg),
16 | _ => log::info!("{}", msg),
17 | };
18 | }
19 | }
20 |
21 | #[allow(dead_code)]
22 | fn main() {}
23 |
--------------------------------------------------------------------------------
/images/inline-gradient-color.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/diffuse/swing/3e735867dc5b57337943297f773969eb6a2eee43/images/inline-gradient-color.png
--------------------------------------------------------------------------------
/images/multi-line-gradient.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/diffuse/swing/3e735867dc5b57337943297f773969eb6a2eee43/images/multi-line-gradient.png
--------------------------------------------------------------------------------
/images/simple-theme.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
288 |
--------------------------------------------------------------------------------
/images/solid-color.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/diffuse/swing/3e735867dc5b57337943297f773969eb6a2eee43/images/solid-color.png
--------------------------------------------------------------------------------
/images/spectral-theme.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
288 |
--------------------------------------------------------------------------------
/images/swing.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/diffuse/swing/3e735867dc5b57337943297f773969eb6a2eee43/images/swing.gif
--------------------------------------------------------------------------------
/images/swing.svg:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
1451 |
--------------------------------------------------------------------------------
/src/color.rs:
--------------------------------------------------------------------------------
1 | //! Color related type definitions and constant values
2 |
3 | use colored::{self, Color::TrueColor};
4 |
5 | /// RGB triplet
6 | #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug, Default)]
7 | pub struct Rgb {
8 | /// red intensity
9 | pub r: u8,
10 | /// green intensity
11 | pub g: u8,
12 | /// blue intensity
13 | pub b: u8,
14 | }
15 |
16 | impl Into for Rgb {
17 | /// Convert Rgb -> Color for easier use with string coloring
18 | fn into(self) -> colored::Color {
19 | TrueColor {
20 | r: self.r,
21 | g: self.g,
22 | b: self.b,
23 | }
24 | }
25 | }
26 |
27 | /// RgbRange defines a linear color range from some start Rgb
28 | /// triplet -> some end Rgb triplet
29 | #[derive(Copy, Clone, Eq, PartialEq, Hash, Debug, Default)]
30 | pub struct RgbRange {
31 | /// start of color range
32 | pub start: Rgb,
33 | /// end of color range
34 | pub end: Rgb,
35 | }
36 |
37 | /// Constant predefined color values
38 | ///
39 | /// Use of these color values is not necessary when
40 | /// creating a theme, but they act as helpful aliases
41 | /// for raw Rgb triplets
42 | #[allow(dead_code)]
43 | pub enum Color {
44 | /// dark magenta
45 | DarkMagenta,
46 | /// magenta
47 | Magenta,
48 | /// dark pink
49 | DarkPink,
50 | /// pink
51 | Pink,
52 | /// dark cyan
53 | DarkCyan,
54 | /// cyan
55 | Cyan,
56 | /// dark blue
57 | DarkBlue,
58 | /// blue
59 | Blue,
60 | /// dark green
61 | DarkGreen,
62 | /// green
63 | Green,
64 | /// dark yellow
65 | DarkYellow,
66 | /// yellow
67 | Yellow,
68 | /// dark orange
69 | DarkOrange,
70 | /// orange
71 | Orange,
72 | /// dark red
73 | DarkRed,
74 | /// red
75 | Red,
76 | }
77 |
78 | impl Color {
79 | /// Return the Rgb triplet associated with a color variant
80 | pub fn value(&self) -> Rgb {
81 | match self {
82 | Color::DarkMagenta => Rgb {
83 | r: 139,
84 | g: 0,
85 | b: 139,
86 | },
87 | Color::Magenta => Rgb {
88 | r: 255,
89 | g: 0,
90 | b: 255,
91 | },
92 | Color::DarkPink => Rgb {
93 | r: 149,
94 | g: 119,
95 | b: 149,
96 | },
97 | Color::Pink => Rgb {
98 | r: 227,
99 | g: 184,
100 | b: 227,
101 | },
102 | Color::DarkCyan => Rgb {
103 | r: 10,
104 | g: 144,
105 | b: 144,
106 | },
107 | Color::Cyan => Rgb {
108 | r: 20,
109 | g: 210,
110 | b: 210,
111 | },
112 | Color::DarkBlue => Rgb {
113 | r: 70,
114 | g: 75,
115 | b: 185,
116 | },
117 | Color::Blue => Rgb {
118 | r: 90,
119 | g: 100,
120 | b: 240,
121 | },
122 | Color::DarkGreen => Rgb {
123 | r: 70,
124 | g: 140,
125 | b: 10,
126 | },
127 | Color::Green => Rgb {
128 | r: 110,
129 | g: 220,
130 | b: 10,
131 | },
132 | Color::DarkYellow => Rgb {
133 | r: 170,
134 | g: 128,
135 | b: 0,
136 | },
137 | Color::Yellow => Rgb {
138 | r: 255,
139 | g: 185,
140 | b: 0,
141 | },
142 | Color::DarkOrange => Rgb {
143 | r: 255,
144 | g: 128,
145 | b: 0,
146 | },
147 | Color::Orange => Rgb {
148 | r: 250,
149 | g: 180,
150 | b: 110,
151 | },
152 | Color::DarkRed => Rgb {
153 | r: 200,
154 | g: 0,
155 | b: 10,
156 | },
157 | Color::Red => Rgb {
158 | r: 255,
159 | g: 60,
160 | b: 10,
161 | },
162 | }
163 | }
164 | }
165 |
166 | #[cfg(test)]
167 | mod tests {
168 | use super::*;
169 |
170 | #[test]
171 | fn rgb_into_color_is_accurate() {
172 | let test_cases = vec![
173 | (Rgb { r: 0, g: 0, b: 0 }, TrueColor { r: 0, g: 0, b: 0 }),
174 | (
175 | Rgb {
176 | r: 127,
177 | g: 128,
178 | b: 129,
179 | },
180 | TrueColor {
181 | r: 127,
182 | g: 128,
183 | b: 129,
184 | },
185 | ),
186 | (
187 | Rgb {
188 | r: 255,
189 | g: 255,
190 | b: 255,
191 | },
192 | TrueColor {
193 | r: 255,
194 | g: 255,
195 | b: 255,
196 | },
197 | ),
198 | ];
199 |
200 | for (rgb, tc) in test_cases {
201 | let c: colored::Color = rgb.into();
202 | assert_eq!(c, tc);
203 | }
204 | }
205 | }
206 |
--------------------------------------------------------------------------------
/src/config.rs:
--------------------------------------------------------------------------------
1 | //! Configuration related definitions and implementation
2 |
3 | use crate::{paint::ColorFormat, sculpt::RecordFormat, theme::Spectral, theme::Theme};
4 | use log::LevelFilter;
5 |
6 | /// Main configuration for a `Logger`
7 | pub struct Config {
8 | /// log level filter (logs below this severity will be ignored)
9 | pub level: LevelFilter,
10 | /// record formatting mode (determines how log records are structurally formatted)
11 | pub record_format: RecordFormat,
12 | /// color formatting mode (determines how log records are colored)
13 | pub color_format: Option,
14 | /// color theme (determines the color palette used to color log records)
15 | pub theme: Box,
16 | /// switch for enabling log splitting to `stderr`
17 | ///
18 | /// - `true`: log `trace` - `info` levels to `stdout` and `warn` - `error` levels to `stderr`
19 | ///
20 | /// - `false`: log all levels to `stdout`
21 | pub use_stderr: bool,
22 | }
23 |
24 | impl Default for Config {
25 | /// Return a `Config` with default values
26 | fn default() -> Config {
27 | Config {
28 | level: LevelFilter::Info,
29 | record_format: RecordFormat::Simple,
30 | color_format: Some(ColorFormat::Solid),
31 | theme: Box::new(Spectral {}),
32 | use_stderr: true,
33 | }
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/lib.rs:
--------------------------------------------------------------------------------
1 | #![doc = include_str!("../README.md")]
2 | #![doc(
3 | html_logo_url = "https://i.imgur.com/xOjqfvy.gif",
4 | html_favicon_url = "https://i.imgur.com/Q7UUHoN.png",
5 | html_playground_url = "https://play.rust-lang.org/"
6 | )]
7 | #![deny(missing_docs)]
8 |
9 | use log::{LevelFilter, Log, Metadata, Record, SetLoggerError};
10 | mod paint;
11 | use paint::LogPainter;
12 | mod sculpt;
13 | use sculpt::LogSculptor;
14 | mod write;
15 | use write::LogWriter;
16 |
17 | pub mod color;
18 | pub mod theme;
19 | pub use color::{Color, Rgb, RgbRange};
20 | pub use paint::ColorFormat;
21 | pub use sculpt::RecordFormat;
22 | pub use theme::Theme;
23 | pub mod config;
24 | pub use config::Config;
25 |
26 | /// Implements log::Log
27 | pub struct Logger {
28 | /// Level-based filter for logs
29 | level_filter: LevelFilter,
30 | /// painter for logs
31 | log_painter: LogPainter,
32 | /// sculptor for logs
33 | log_sculptor: LogSculptor,
34 | /// writer for logs
35 | log_writer: LogWriter,
36 | }
37 |
38 | impl Logger {
39 | /// Create a new Logger with a default configuration
40 | pub fn new() -> Logger {
41 | Logger::with_config(Config::default())
42 | }
43 |
44 | /// Create a new Logger with a custom configuration
45 | ///
46 | /// # Arguments
47 | ///
48 | /// * `config` - configuration for this logger
49 | pub fn with_config(config: Config) -> Logger {
50 | Logger {
51 | log_sculptor: LogSculptor::new(config.record_format),
52 | level_filter: config.level,
53 | log_painter: LogPainter::new(config.theme, config.color_format),
54 | log_writer: LogWriter::new(config.use_stderr),
55 | }
56 | }
57 |
58 | /// Initialize this logger
59 | pub fn init(self) -> Result<(), SetLoggerError> {
60 | log::set_boxed_logger(Box::new(self)).map(|()| log::set_max_level(LevelFilter::Trace))
61 | }
62 | }
63 |
64 | impl Log for Logger {
65 | /// Check if this message should be logged
66 | fn enabled(&self, metadata: &Metadata) -> bool {
67 | metadata.level() <= self.level_filter
68 | }
69 |
70 | /// Log a message/record
71 | ///
72 | /// # Arguments
73 | ///
74 | /// * `record` - the record to log
75 | fn log(&self, record: &Record) {
76 | if !self.enabled(record.metadata()) {
77 | return;
78 | }
79 |
80 | let mut msg = self.log_sculptor.sculpt(record);
81 | msg = self.log_painter.paint(msg, record.level());
82 | self.log_writer.write(msg, record.level());
83 | }
84 |
85 | fn flush(&self) {}
86 | }
87 |
88 | #[cfg(test)]
89 | mod tests {
90 | use super::*;
91 | use log::Level;
92 |
93 | #[test]
94 | fn enabled_filters_levels() {
95 | let config = Config {
96 | level: LevelFilter::Warn,
97 | ..Default::default()
98 | };
99 | let logger = Logger::with_config(config);
100 | let mut mb = Metadata::builder();
101 |
102 | assert!(!logger.enabled(&mut mb.level(Level::Trace).build()));
103 | assert!(!logger.enabled(&mut mb.level(Level::Debug).build()));
104 | assert!(!logger.enabled(&mut mb.level(Level::Info).build()));
105 | assert!(logger.enabled(&mut mb.level(Level::Warn).build()));
106 | assert!(logger.enabled(&mut mb.level(Level::Error).build()));
107 | }
108 |
109 | #[test]
110 | fn enabled_with_off_level_filter_is_always_false() {
111 | let config = Config {
112 | level: LevelFilter::Off,
113 | ..Default::default()
114 | };
115 | let logger = Logger::with_config(config);
116 | let mut mb = Metadata::builder();
117 |
118 | assert!(!logger.enabled(&mut mb.level(Level::Trace).build()));
119 | assert!(!logger.enabled(&mut mb.level(Level::Debug).build()));
120 | assert!(!logger.enabled(&mut mb.level(Level::Info).build()));
121 | assert!(!logger.enabled(&mut mb.level(Level::Warn).build()));
122 | assert!(!logger.enabled(&mut mb.level(Level::Error).build()));
123 | }
124 |
125 | #[test]
126 | fn log_handles_empty_record() {
127 | let config = Config::default();
128 | let logger = Logger::with_config(config);
129 |
130 | // create record with fields set to empty strings
131 | let rec = Record::builder()
132 | .args(format_args!(""))
133 | .level(Level::Info)
134 | .target("")
135 | .build();
136 |
137 | // this shouldn't panic
138 | logger.log(&rec);
139 | }
140 | }
141 |
--------------------------------------------------------------------------------
/src/paint.rs:
--------------------------------------------------------------------------------
1 | use crate::{Rgb, RgbRange, Theme};
2 | use colored::Colorize;
3 | use log::Level;
4 | use std::collections::HashMap;
5 | use std::sync::Mutex;
6 | use unicode_segmentation::UnicodeSegmentation;
7 |
8 | /// Color formatting mode that determines how log records are colored/how a theme
9 | /// is applied to log records
10 | pub enum ColorFormat {
11 | /// solid color(s) applied from a theme to log lines
12 | Solid,
13 | /// linear color gradient applied over characters in a single line, with arg for number of steps
14 | /// in gradient (how many characters it will take to go from the starting color to the ending color
15 | /// for each level)
16 | InlineGradient(usize),
17 | /// linear color gradient applied over multiple lines, with arg for number of steps in gradient (how
18 | /// many lines it will take to go from the starting color to the ending color for each level)
19 | MultiLineGradient(usize),
20 | }
21 |
22 | /// Get the distance, [0-1], that `x` falls along the line from 0-`n`
23 | ///
24 | /// Dist will move in the direction:
25 | /// - 0 -> 1 when (`x` % `2n`) <= `n`
26 | /// - 1 -> 0 when `n` < (`x` % `2n`) < `2n`
27 | ///
28 | /// If used with linear gradients, this oscillating dist will avoid the harsh visual
29 | /// transition when wrapping around from 1 -> 0 (e.g. 0.9, 1.0, 0.0, 0.1 will not be
30 | /// a smooth transition)
31 | ///
32 | /// # Arguments
33 | ///
34 | /// * `x` - some number whose value, `x` % `2n`, will be considered the distance along the line 0-`n`
35 | /// * `n` - upper limit of range 0-`n`
36 | fn oscillate_dist(x: usize, n: usize) -> f32 {
37 | let n = if n == 0 { 1 } else { n };
38 | (x.wrapping_add(n) % n.wrapping_mul(2)).abs_diff(n) as f32 / (n as f32)
39 | }
40 |
41 | /// Compute a new color `dist` distance along the linear
42 | /// gradient from start to end of `range`
43 | ///
44 | /// `dist` will be clamped to the range 0.0 - 1.0
45 | ///
46 | /// # Arguments
47 | ///
48 | /// * `range` - bounding color range for this linear gradient
49 | /// * `dist` - desired distance along linear gradient (0.0 - 1.0)
50 | fn linear_gradient(range: &RgbRange, dist: f32) -> Rgb {
51 | let dist = dist.clamp(0.0, 1.0);
52 | let start = &range.start;
53 | let end = &range.end;
54 |
55 | let r_range = (end.r as f32) - (start.r as f32);
56 | let g_range = (end.g as f32) - (start.g as f32);
57 | let b_range = (end.b as f32) - (start.b as f32);
58 |
59 | Rgb {
60 | r: ((start.r as f32) + (dist * r_range)) as u8,
61 | g: ((start.g as f32) + (dist * g_range)) as u8,
62 | b: ((start.b as f32) + (dist * b_range)) as u8,
63 | }
64 | }
65 |
66 | /// Paint/color logs using arbitrary themes and formats
67 | pub struct LogPainter {
68 | /// Count of how many lines are logged at each level,
69 | /// for use with coloring
70 | lines_logged: Mutex>,
71 | /// color theme (determines the color palette used to color log records)
72 | theme: Box,
73 | /// color formatting mode (determines how log records are colored)
74 | color_format: Option,
75 | }
76 |
77 | impl LogPainter {
78 | /// Create a new LogPainter
79 | ///
80 | /// # Arguments
81 | ///
82 | /// * `theme` - theme used for color selection
83 | /// * `color_format` - format used for painting
84 | pub fn new(theme: Box, color_format: Option) -> LogPainter {
85 | LogPainter {
86 | lines_logged: Mutex::new(HashMap::new()),
87 | theme,
88 | color_format,
89 | }
90 | }
91 |
92 | /// Paint/color a log line, based on the current logger configuration
93 | ///
94 | /// Arguments
95 | ///
96 | /// * `msg` - message to paint/color
97 | /// * `level` - level of this log line
98 | pub fn paint(&self, msg: String, level: Level) -> String {
99 | if self.color_format.is_none() {
100 | return msg;
101 | }
102 |
103 | let line = match self.color_format.as_ref().unwrap() {
104 | ColorFormat::Solid => self.paint_solid(msg, level),
105 | ColorFormat::InlineGradient(steps) => self.paint_inline_gradient(msg, level, *steps),
106 | ColorFormat::MultiLineGradient(steps) => {
107 | let l = self.paint_multi_line_gradient(msg, level, *steps);
108 |
109 | // increment line counter for this level
110 | self.lines_logged
111 | .lock()
112 | .unwrap()
113 | .entry(level)
114 | .and_modify(|e| *e = e.wrapping_add(1))
115 | .or_insert(0);
116 |
117 | return l;
118 | }
119 | };
120 |
121 | return line;
122 | }
123 |
124 | /// Paint strings using one color per line,
125 | /// chosen based on log level
126 | ///
127 | /// # Arguments
128 | ///
129 | /// * `msg` - message to color
130 | /// * `level` - level of this log line
131 | fn paint_solid(&self, msg: String, level: Level) -> String {
132 | let color = self.theme.solid(level);
133 | msg.color(color).to_string()
134 | }
135 |
136 | /// Apply linear color gradient across the graphemes in a string
137 | ///
138 | /// # Arguments
139 | ///
140 | /// * `msg` - message to color
141 | /// * `level` - level of this log line
142 | /// * `steps` - number of steps in gradient
143 | fn paint_inline_gradient(&self, msg: String, level: Level, steps: usize) -> String {
144 | msg.graphemes(true)
145 | .enumerate()
146 | .map(|(i, c)| {
147 | let dist = oscillate_dist(i, steps);
148 | let color = linear_gradient(&self.theme.range(level), dist);
149 | c.color(color).to_string()
150 | })
151 | .collect::>()
152 | .join("")
153 | }
154 |
155 | /// Apply a linear color gradient over multiple lines
156 | ///
157 | /// An independent linear color gradient will be applied across
158 | /// all lines logged at each level (e.g. `INFO` line color can change
159 | /// from green -> cyan as lines are logged, while lines logged at other
160 | /// levels move independently in their own gradient color ranges)
161 | ///
162 | /// # Arguments
163 | ///
164 | /// * `msg` - message to color
165 | /// * `level` - level of this log line
166 | /// * `steps` - number of steps in gradient
167 | fn paint_multi_line_gradient(&self, msg: String, level: Level, steps: usize) -> String {
168 | let lines_logged = *self.lines_logged.lock().unwrap().entry(level).or_insert(0);
169 | let dist = oscillate_dist(lines_logged, steps);
170 | let color = linear_gradient(&self.theme.range(level), dist);
171 | msg.color(color).to_string()
172 | }
173 | }
174 |
175 | #[cfg(test)]
176 | mod tests {
177 | use super::*;
178 | use crate::theme;
179 | use num::NumCast;
180 |
181 | // helpers
182 |
183 | /// Assert that two values are equal within some range, `eps`
184 | ///
185 | /// # Arguments
186 | ///
187 | /// * `a` - first value to compare
188 | /// * `b` - second value to compare
189 | /// * `eps` - max distance to consider diff of values equal within
190 | fn assert_eq_with_eps(a: T, b: T, eps: T) {
191 | let a: f64 = NumCast::from(a).unwrap();
192 | let b: f64 = NumCast::from(b).unwrap();
193 | let eps: f64 = NumCast::from(eps).unwrap();
194 |
195 | if (a - b).abs() > eps {
196 | panic!("{} and {} were not equal", a, b);
197 | }
198 | }
199 |
200 | /// To account for differences in the floating point math used to
201 | /// calculate colors along a gradient, this function compares the
202 | /// values in two Rgb structs within some range (+/- some value)
203 | ///
204 | /// # Arguments
205 | ///
206 | /// * `lhs` - first color in comparison
207 | /// * `rhs` - second color in comparison
208 | /// * `eps` - max distance to consider diff of r/g/b values equal within
209 | fn assert_rgb_eq(lhs: Rgb, rhs: Rgb, eps: Option) {
210 | let eps = eps.unwrap_or(1);
211 |
212 | assert_eq_with_eps(lhs.r, rhs.r, eps);
213 | assert_eq_with_eps(lhs.g, rhs.g, eps);
214 | assert_eq_with_eps(lhs.b, rhs.b, eps);
215 | }
216 |
217 | /// Assert that `f` gives a uniquely colored output for a string
218 | /// logged at each of the possible log levels
219 | ///
220 | /// # Arguments
221 | ///
222 | /// * `f` - function to color a string by log level
223 | fn assert_logs_colored_by_level(f: &dyn Fn(&LogPainter, String, Level) -> String) {
224 | // create a painter
225 | let theme = Box::new(theme::Simple {});
226 | let painter = LogPainter::new(theme, Some(ColorFormat::Solid));
227 |
228 | // run `f` on `msg` with each level to make sure that
229 | // no two levels give the same colored output
230 | let msg = "foo".to_string();
231 | let lines = [
232 | f(&painter, msg.clone(), Level::Trace),
233 | f(&painter, msg.clone(), Level::Debug),
234 | f(&painter, msg.clone(), Level::Info),
235 | f(&painter, msg.clone(), Level::Warn),
236 | f(&painter, msg.clone(), Level::Error),
237 | ];
238 |
239 | // check that each colored line is unique
240 | for (i, line) in lines.iter().enumerate() {
241 | for line1 in lines.iter().skip(i + 1) {
242 | if line == line1 {
243 | panic!("\"{}\" and \"{}\" had different levels but generated the same formatted line", line, line1);
244 | }
245 | }
246 | }
247 | }
248 |
249 | // tests
250 |
251 | #[test]
252 | fn linear_gradient_calculates_correct_color() {
253 | let r = RgbRange {
254 | start: Rgb { r: 0, g: 0, b: 0 },
255 | end: Rgb {
256 | r: 255,
257 | g: 255,
258 | b: 255,
259 | },
260 | };
261 |
262 | assert_rgb_eq(linear_gradient(&r, 0.0), Rgb { r: 0, g: 0, b: 0 }, None);
263 | assert_rgb_eq(
264 | linear_gradient(&r, 0.25),
265 | Rgb {
266 | r: 64,
267 | g: 64,
268 | b: 64,
269 | },
270 | None,
271 | );
272 | assert_rgb_eq(
273 | linear_gradient(&r, 0.5),
274 | Rgb {
275 | r: 128,
276 | g: 128,
277 | b: 128,
278 | },
279 | None,
280 | );
281 | assert_rgb_eq(
282 | linear_gradient(&r, 0.75),
283 | Rgb {
284 | r: 190,
285 | g: 190,
286 | b: 190,
287 | },
288 | None,
289 | );
290 | assert_rgb_eq(
291 | linear_gradient(&r, 1.0),
292 | Rgb {
293 | r: 255,
294 | g: 255,
295 | b: 255,
296 | },
297 | None,
298 | );
299 | }
300 |
301 | #[test]
302 | fn linear_gradient_clamps_dist() {
303 | let r = RgbRange {
304 | start: Rgb { r: 0, g: 0, b: 0 },
305 | end: Rgb {
306 | r: 255,
307 | g: 255,
308 | b: 255,
309 | },
310 | };
311 |
312 | let expected = Rgb { r: 0, g: 0, b: 0 };
313 | assert_rgb_eq(linear_gradient(&r, -1.0), expected, None);
314 |
315 | let expected = Rgb {
316 | r: 255,
317 | g: 255,
318 | b: 255,
319 | };
320 | assert_rgb_eq(linear_gradient(&r, 100.0), expected, None);
321 | }
322 |
323 | #[test]
324 | fn oscillate_dist_oscillates() {
325 | assert_eq_with_eps(oscillate_dist(0, 255), 0.0, 1e-2);
326 | assert_eq_with_eps(oscillate_dist(128, 255), 0.5, 1e-2);
327 | assert_eq_with_eps(oscillate_dist(255, 255), 1.0, 1e-2);
328 | assert_eq_with_eps(oscillate_dist(256, 255), 1.0 - (1.0 / 255.0), 1e-2);
329 | assert_eq_with_eps(oscillate_dist(383, 255), 0.5, 1e-2);
330 | assert_eq_with_eps(oscillate_dist(510, 255), 0.0, 1e-2);
331 | assert_eq_with_eps(oscillate_dist(638, 255), 0.5, 1e-2);
332 | assert_eq_with_eps(oscillate_dist(765, 255), 1.0, 1e-2);
333 | assert_eq_with_eps(
334 | oscillate_dist(usize::max_value(), 255),
335 | oscillate_dist(usize::max_value() - 255, 255),
336 | 1e-2,
337 | );
338 | assert_eq_with_eps(oscillate_dist(12, usize::max_value()), 1.0, 1e-2);
339 | assert_eq_with_eps(oscillate_dist(257, usize::max_value()), 1.0, 1e-2);
340 | assert_eq_with_eps(
341 | oscillate_dist(usize::max_value(), usize::max_value()),
342 | 1.0,
343 | 1e-2,
344 | );
345 | }
346 |
347 | #[test]
348 | fn oscillate_dist_handles_0_n() {
349 | // this shouldn't panic
350 | oscillate_dist(0, 0);
351 | }
352 |
353 | #[test]
354 | fn paint_solid_colors_by_level() {
355 | assert_logs_colored_by_level(&LogPainter::paint_solid);
356 | }
357 |
358 | #[test]
359 | fn paint_inline_gradient_colors_by_level() {
360 | let color_fn = |painter: &LogPainter, msg: String, level: Level| -> String {
361 | painter.paint_inline_gradient(msg, level, 20)
362 | };
363 |
364 | assert_logs_colored_by_level(&color_fn);
365 | }
366 |
367 | #[test]
368 | fn paint_multi_line_gradient_colors_by_level() {
369 | let color_fn = |painter: &LogPainter, msg: String, level: Level| -> String {
370 | painter.paint_multi_line_gradient(msg, level, 20)
371 | };
372 |
373 | assert_logs_colored_by_level(&color_fn);
374 | }
375 |
376 | #[test]
377 | fn paint_fns_handle_empty_msg() {
378 | let theme = Box::new(theme::Simple {});
379 | let color_format = Some(ColorFormat::Solid);
380 | let painter = LogPainter::new(theme, color_format);
381 |
382 | // none of these calls should panic with an empty message
383 | painter.paint_solid("".to_string(), Level::Warn);
384 | painter.paint_inline_gradient("".to_string(), Level::Warn, 10);
385 | painter.paint_multi_line_gradient("".to_string(), Level::Warn, 10);
386 | }
387 |
388 | #[test]
389 | fn paint_with_none_format_returns_orig() {
390 | let theme = Box::new(theme::Simple {});
391 | let color_format = None;
392 | let painter = LogPainter::new(theme, color_format);
393 |
394 | // input msg should not be altered by None color format
395 | let msg = "foo".to_string();
396 | assert_eq!(painter.paint(msg.clone(), Level::Info), msg);
397 | }
398 |
399 | #[test]
400 | fn paint_log_with_inline_gradient_uses_steps_arg() {
401 | let theme = Box::new(theme::Simple {});
402 | let color_format = Some(ColorFormat::InlineGradient(2));
403 | let painter = LogPainter::new(theme, color_format);
404 | let msgs = vec!["0000000000".to_string(), "नमस्तेनमस्तेनमस्तेनमस्तेनमस्ते".to_string()];
405 |
406 | for msg in msgs {
407 | let msg_colored = painter.paint(msg.clone(), Level::Info);
408 |
409 | // collect ANSI 24-bit escape sequences to compare color of each grapheme
410 | let words = msg_colored.unicode_words().collect::>();
411 | let num_words = words.len();
412 | let graphemes = msg.graphemes(true).collect::>().len();
413 | let escape_seqs = words
414 | .into_iter()
415 | .step_by(num_words / graphemes)
416 | .collect::>();
417 |
418 | // check that gradient restarts at index 4 (2 * steps)
419 | //
420 | // it restarts at 4 instead of 2 because the gradient is first
421 | // traversed from start to end, then from end to start, then start to end
422 | // again, oscillating this way indefinitely
423 | assert_ne!(escape_seqs[0], escape_seqs[1]);
424 | assert_eq!(escape_seqs[0], escape_seqs[4]);
425 | assert_eq!(escape_seqs[1], escape_seqs[5]);
426 | assert_eq!(escape_seqs[2], escape_seqs[6]);
427 | assert_eq!(escape_seqs[3], escape_seqs[7]);
428 | }
429 | }
430 |
431 | #[test]
432 | fn paint_log_with_multi_line_gradient_changes_color_within_level() {
433 | let theme = Box::new(theme::Simple {});
434 | let color_format = Some(ColorFormat::MultiLineGradient(20));
435 | let painter = LogPainter::new(theme, color_format);
436 | let msg = "foo".to_string();
437 |
438 | // the color should change each time a message is logged,
439 | // since the multi-line gradient color format should create
440 | // a color gradient over multiple lines (under each level)
441 | let assert_color_changes_within_level = |level: Level| {
442 | let mut last_logged = "".to_string();
443 |
444 | for _ in 0..10 {
445 | let l = painter.paint(msg.clone(), level);
446 | assert_ne!(last_logged, l);
447 | last_logged = l;
448 | }
449 | };
450 |
451 | assert_color_changes_within_level(Level::Trace);
452 | assert_color_changes_within_level(Level::Debug);
453 | assert_color_changes_within_level(Level::Info);
454 | assert_color_changes_within_level(Level::Warn);
455 | assert_color_changes_within_level(Level::Error);
456 | }
457 |
458 | #[test]
459 | fn paint_log_with_multi_line_gradient_uses_steps_arg() {
460 | // use multi-line gradient with 2 steps in the linear gradient
461 | let steps: usize = 2;
462 | let theme = Box::new(theme::Simple {});
463 | let color_format = Some(ColorFormat::MultiLineGradient(steps));
464 | let painter = LogPainter::new(theme, color_format);
465 | let msg = "foo".to_string();
466 |
467 | let lines = vec![
468 | // gradient starts going from start -> end here
469 | painter.paint(msg.clone(), Level::Info),
470 | painter.paint(msg.clone(), Level::Info),
471 | // end -> start
472 | painter.paint(msg.clone(), Level::Info),
473 | painter.paint(msg.clone(), Level::Info),
474 | // gradient should start over here, start -> end
475 | painter.paint(msg.clone(), Level::Info),
476 | painter.paint(msg.clone(), Level::Info),
477 | // end -> start
478 | painter.paint(msg.clone(), Level::Info),
479 | painter.paint(msg.clone(), Level::Info),
480 | ];
481 |
482 | // check that gradient restarts at index 4 (2 * steps)
483 | //
484 | // it restarts at 4 instead of 2 because the gradient is first
485 | // traversed from start to end, then from end to start, then start to end
486 | // again, oscillating this way indefinitely
487 | assert_ne!(lines[0], lines[1]);
488 | assert_eq!(lines[0], lines[4]);
489 | assert_eq!(lines[1], lines[5]);
490 | assert_eq!(lines[2], lines[6]);
491 | assert_eq!(lines[3], lines[7]);
492 | }
493 | }
494 |
--------------------------------------------------------------------------------
/src/sculpt.rs:
--------------------------------------------------------------------------------
1 | use log::Record;
2 | use serde_json::json;
3 | use time::format_description::well_known::Iso8601;
4 | use time::OffsetDateTime;
5 |
6 | /// Record formatting mode that determines how log records are structured
7 | pub enum RecordFormat {
8 | /// JSON format
9 | Json,
10 | /// simple log format ` [] - `
11 | Simple,
12 | /// custom record formatter provided by client code
13 | Custom(Box String>),
14 | }
15 |
16 | /// Sculpt/create structurally formatted string logs from raw log records
17 | pub struct LogSculptor {
18 | /// record formatting mode (determines how log records are structurally formatted)
19 | pub record_format: RecordFormat,
20 | }
21 |
22 | impl LogSculptor {
23 | /// Create a new LogSculptor using the provided record format
24 | ///
25 | /// # Arguments
26 | ///
27 | /// * `record_format` - the structural format to use when sculpting records
28 | pub fn new(record_format: RecordFormat) -> LogSculptor {
29 | LogSculptor { record_format }
30 | }
31 |
32 | /// Convert a log record into a formatted string, based on the current logger configuration
33 | ///
34 | /// # Arguments
35 | ///
36 | /// * `record` - the log record to format
37 | pub fn sculpt(&self, record: &Record) -> String {
38 | let now = OffsetDateTime::now_utc()
39 | .format(&Iso8601::DEFAULT)
40 | .expect("Failed to format time as ISO 8601");
41 |
42 | match &self.record_format {
43 | RecordFormat::Json => json!({
44 | "time": now,
45 | "level": record.level(),
46 | "target": record.target(),
47 | "message": record.args(),
48 | })
49 | .to_string(),
50 | RecordFormat::Simple => {
51 | format!(
52 | "{} [{}] {} - {}",
53 | now,
54 | record.target(),
55 | record.level(),
56 | record.args()
57 | )
58 | }
59 | RecordFormat::Custom(f) => f(record),
60 | }
61 | }
62 | }
63 |
64 | #[cfg(test)]
65 | mod tests {
66 | use super::*;
67 | use log::Level;
68 |
69 | #[test]
70 | fn sculpt_presets_return_non_empty() {
71 | for fmt in vec![RecordFormat::Json, RecordFormat::Simple] {
72 | let sculptor = LogSculptor::new(fmt);
73 |
74 | // create normal test record
75 | let rec = Record::builder()
76 | .args(format_args!("foo"))
77 | .level(Level::Info)
78 | .target("test")
79 | .build();
80 |
81 | assert!(!sculptor.sculpt(&rec).is_empty());
82 |
83 | // create record with empty args and target
84 | let rec = Record::builder()
85 | .args(format_args!(""))
86 | .level(Level::Info)
87 | .target("")
88 | .build();
89 |
90 | // record should still give non-empty log lines
91 | assert!(!sculptor.sculpt(&rec).is_empty());
92 | }
93 | }
94 |
95 | #[test]
96 | fn sculpt_custom_formats_correctly() {
97 | let test_cases = vec![
98 | (RecordFormat::Custom(Box::new(|_| "".to_string())), ""),
99 | (
100 | RecordFormat::Custom(Box::new(|r| format!("{} {}", r.level(), r.args()))),
101 | "INFO foo",
102 | ),
103 | (
104 | RecordFormat::Custom(Box::new(|r| {
105 | format!("{} [{}] {}", r.level(), r.target(), r.args())
106 | })),
107 | "INFO [test] foo",
108 | ),
109 | ];
110 |
111 | let rec = Record::builder()
112 | .args(format_args!("foo"))
113 | .level(Level::Info)
114 | .target("test")
115 | .build();
116 |
117 | for (fmt, expected) in test_cases {
118 | let sculptor = LogSculptor::new(fmt);
119 | assert_eq!(sculptor.sculpt(&rec), expected);
120 | }
121 | }
122 | }
123 |
--------------------------------------------------------------------------------
/src/theme.rs:
--------------------------------------------------------------------------------
1 | //! Theme trait definition and predefined themes
2 | //!
3 | //! See examples/custom-theme.rs for an example of defining a
4 | //! custom theme
5 |
6 | use crate::color::{Color, Rgb, RgbRange};
7 | use log::Level;
8 |
9 | /// Define a log level specific color palette to be injected into
10 | /// color formatting
11 | pub trait Theme: Send + Sync {
12 | /// return the representative solid color for this theme at each level
13 | fn solid(&self, level: Level) -> Rgb;
14 | /// return the bounding color range for this theme at each level
15 | fn range(&self, level: Level) -> RgbRange;
16 | }
17 |
18 | /// Basic log level colors
19 | #[derive(Clone)]
20 | pub struct Simple {}
21 |
22 | impl Theme for Simple {
23 | fn solid(&self, level: Level) -> Rgb {
24 | self.range(level).start
25 | }
26 |
27 | fn range(&self, level: Level) -> RgbRange {
28 | match level {
29 | Level::Trace => RgbRange {
30 | start: Color::DarkPink.value(),
31 | end: Color::Pink.value(),
32 | },
33 | Level::Debug => RgbRange {
34 | start: Color::DarkCyan.value(),
35 | end: Color::Cyan.value(),
36 | },
37 | Level::Info => RgbRange {
38 | start: Color::DarkGreen.value(),
39 | end: Color::Green.value(),
40 | },
41 | Level::Warn => RgbRange {
42 | start: Color::DarkOrange.value(),
43 | end: Color::Orange.value(),
44 | },
45 | Level::Error => RgbRange {
46 | start: Color::DarkRed.value(),
47 | end: Color::Red.value(),
48 | },
49 | }
50 | }
51 | }
52 |
53 | /// Move down the color spectrum by level
54 | #[derive(Clone)]
55 | pub struct Spectral {}
56 |
57 | impl Theme for Spectral {
58 | fn solid(&self, level: Level) -> Rgb {
59 | self.range(level).end
60 | }
61 |
62 | fn range(&self, level: Level) -> RgbRange {
63 | match level {
64 | Level::Trace => RgbRange {
65 | start: Color::DarkMagenta.value(),
66 | end: Color::Pink.value(),
67 | },
68 | Level::Debug => RgbRange {
69 | start: Color::DarkBlue.value(),
70 | end: Color::Cyan.value(),
71 | },
72 | Level::Info => RgbRange {
73 | start: Color::DarkCyan.value(),
74 | end: Color::Green.value(),
75 | },
76 | Level::Warn => RgbRange {
77 | start: Color::DarkYellow.value(),
78 | end: Color::Orange.value(),
79 | },
80 | Level::Error => RgbRange {
81 | start: Color::DarkRed.value(),
82 | end: Color::Red.value(),
83 | },
84 | }
85 | }
86 | }
87 |
--------------------------------------------------------------------------------
/src/write.rs:
--------------------------------------------------------------------------------
1 | use colored::Colorize;
2 | use log::Level;
3 | use std::io;
4 | use std::io::Write;
5 | use std::sync::Mutex;
6 |
7 | /// Write logs to stdout/stderr with synchronization
8 | pub struct LogWriter {
9 | /// switch for enabling log splitting to `stderr`
10 | ///
11 | /// - `true`: log `trace` - `info` levels to `stdout` and `warn` - `error` levels to `stderr`
12 | ///
13 | /// - `false`: log all levels to `stdout`
14 | use_stderr: bool,
15 | /// guard against interleaving from simultaneous writes to stdout + stderr
16 | write_mtx: Mutex<()>,
17 | /// handle to stdout
18 | stdout: io::Stdout,
19 | /// handle to stderr
20 | stderr: io::Stderr,
21 | }
22 |
23 | impl LogWriter {
24 | /// Create a new LogWriter
25 | pub fn new(use_stderr: bool) -> LogWriter {
26 | LogWriter {
27 | use_stderr,
28 | write_mtx: Mutex::new(()),
29 | stdout: io::stdout(),
30 | stderr: io::stderr(),
31 | }
32 | }
33 |
34 | /// Write log message to output destination
35 | ///
36 | /// # Arguments
37 | ///
38 | /// * `msg` - the log message to write
39 | /// * `level` - the level of this log message
40 | pub fn write(&self, msg: String, level: Level) {
41 | // stdout and stderr already have their own locks, but
42 | // there is nothing preventing logs simultaneously written
43 | // to stdout + stderr from being interleaved in the console
44 | //
45 | // this guard synchronizes writes so that stdout will not be
46 | // interleaved with stderr
47 | let _lk = self.write_mtx.lock().unwrap();
48 |
49 | match level {
50 | Level::Warn | Level::Error => {
51 | if self.use_stderr {
52 | let _ = writeln!(self.stderr.lock(), "{}", msg.bold());
53 | } else {
54 | let _ = writeln!(self.stdout.lock(), "{}", msg.bold());
55 | }
56 | }
57 | _ => {
58 | let _ = writeln!(self.stdout.lock(), "{}", msg);
59 | }
60 | };
61 | }
62 | }
63 |
64 | #[cfg(test)]
65 | mod tests {
66 | use super::*;
67 |
68 | #[test]
69 | fn write_handles_empty_msg() {
70 | let levels = vec![
71 | Level::Trace,
72 | Level::Debug,
73 | Level::Info,
74 | Level::Warn,
75 | Level::Error,
76 | ];
77 |
78 | // using stderr
79 | let writer = LogWriter::new(true);
80 |
81 | for level in levels.iter() {
82 | writer.write("".to_string(), *level);
83 | }
84 |
85 | // not using stderr
86 | let writer = LogWriter::new(false);
87 |
88 | for level in levels.iter() {
89 | writer.write("".to_string(), *level);
90 | }
91 | }
92 | }
93 |
--------------------------------------------------------------------------------