├── .gitignore ├── CHANGELOG.md ├── CONTRIBUTING.md ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── examples └── trace-yew-app │ ├── .gitignore │ ├── Cargo.toml │ ├── Trunk.toml │ ├── index.html │ └── src │ └── main.rs ├── rustfmt.toml └── src ├── console_writer.rs ├── lib.rs └── performance_layer.rs /.gitignore: -------------------------------------------------------------------------------- 1 | /Cargo.lock 2 | /target 3 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## Version 0.1.3 2 | 3 | - Add `MakeWebConsoleWriter`, a more configurable alternative to``MakeConsoleWriter`. 4 | `MakeWebConsoleWriter::new()` is a drop-in replacement for the old `MakeConsoleWriter` constructor. 5 | - Add `MakeWebConsoleWriter::with_pretty_level()` to print a label denoting the level of the logged event. 6 | 7 | ## Version 0.1.2 8 | 9 | - Change logging method of `Level::TRACE` to `console.debug`. 10 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contribution Guide 2 | 3 | Contributions are welcome! Before starting a significant amount of work, you can also open an issue to discuss it first. 4 | 5 | ## Setting up your local development environment 6 | 7 | To test changes, you can use the sample yew app found in `examples/trace-yew-app`. You need to add the Wasm target and install Trunk to compile this: 8 | 9 | ```bash 10 | rustup target add wasm32-unknown-unknown 11 | cargo install trunk 12 | ``` 13 | 14 | ## Linting 15 | 16 | The following command formats the code using Rustfmt: 17 | 18 | ```bash 19 | cargo +nightly fmt 20 | ``` 21 | 22 | ## Writing APIs 23 | 24 | When building new APIs, think about what it would be like to use them. Would this API cause confusing and hard to pin error mesages? Would this API integrate well with other APIs? Is it intuitive to use this API? 25 | 26 | Below, you can find some useful guidance and best practices on how to write APIs. These are only _guidelines_ and while they are helpful and should be followed where possible, in some cases, it may not be possible to do so. 27 | 28 | - [The Rust API Guidelines](https://rust-lang.github.io/api-guidelines/) 29 | - [Elegant Library APIs in Rust](https://deterministic.space/elegant-apis-in-rust.html) 30 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "tracing-web" 3 | version = "0.1.3" 4 | edition = "2021" 5 | authors = [ 6 | "Martin Molzer ", 7 | ] 8 | license = "MIT OR Apache-2.0" 9 | keywords = ["web", "wasm", "tracing", "log"] 10 | categories = ["development-tools::debugging", "wasm", "web-programming"] 11 | description = "A tracing compatible subscriber layer for web platforms." 12 | readme = "README.md" 13 | repository = "https://github.com/WorldSEnder/tracing-web" 14 | 15 | [dependencies] 16 | js-sys = "0.3.59" 17 | tracing-core = { version = "0.1.29", default-features = false } 18 | tracing-subscriber = { version = "0.3.15", default-features = false, features = ["fmt"] } 19 | wasm-bindgen = { version = "0.2.82", default-features = false } 20 | web-sys = { version = "0.3.59", features = ["console"], default-features = false } 21 | 22 | [dev-dependencies.tracing-subscriber] 23 | version = "0.3.15" 24 | features = ["time"] 25 | 26 | [package.metadata.docs.rs] 27 | all-features = true 28 | rustdoc-args = ["--cfg", "docsrs"] 29 | 30 | [workspace] 31 | members = [ 32 | ".", 33 | "examples/trace-yew-app" 34 | ] 35 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2022 Martin Molzer 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2022 Martin Molzer 2 | 3 | Permission is hereby granted, free of charge, to any 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE. 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## tracing-web 2 | 3 | A [`tracing`] compatible subscriber layer for web platforms. 4 | 5 | [![Crates.io][crates-badge]][crates-url] 6 | [![Documentation][docs-badge]][docs-url] 7 | [![MIT licensed][mit-badge]][mit-url] 8 | [![Apache licensed][apache-badge]][apache-url] 9 | 10 | [Documentation][docs-url] 11 | 12 | [`tracing`]: https://crates.io/crates/tracing 13 | [crates-badge]: https://img.shields.io/crates/v/tracing-web.svg 14 | [crates-url]: https://crates.io/crates/tracing-web 15 | [docs-badge]: https://docs.rs/tracing-web/badge.svg 16 | [docs-url]: https://docs.rs/tracing-web 17 | [mit-badge]: https://img.shields.io/badge/license-MIT-blue.svg 18 | [mit-url]: LICENSE-MIT 19 | [apache-badge]: https://img.shields.io/badge/license-Apache-blue.svg 20 | [apache-url]: LICENSE-APACHE 21 | 22 | # Overview 23 | 24 | `tracing-web` can be used in conjunction with the [`tracing-subscriber`] crate to quickly install a 25 | subscriber that emits messages to the dev-tools console, and events to the [Performance API]. An example 26 | configuration can look like 27 | 28 | ```rust 29 | use tracing_web::{MakeWebConsoleWriter, performance_layer}; 30 | use tracing_subscriber::fmt::format::Pretty; 31 | use tracing_subscriber::prelude::*; 32 | 33 | fn main() { 34 | let fmt_layer = tracing_subscriber::fmt::layer() 35 | .with_ansi(false) // Only partially supported across browsers 36 | .without_time() // std::time is not available in browsers, see note below 37 | .with_writer(MakeWebConsoleWriter::new()); // write events to the console 38 | let perf_layer = performance_layer() 39 | .with_details_from_fields(Pretty::default()); 40 | 41 | tracing_subscriber::registry() 42 | .with(fmt_layer) 43 | .with(perf_layer) 44 | .init(); // Install these as subscribers to tracing events 45 | 46 | todo!("write your awesome application"); 47 | } 48 | ``` 49 | 50 | Note: You can alternatively use `.with_timer(UtcTime::rfc_3339())` with [`UtcTime`] on `web` targets if you enable 51 | the `wasm-bindgen` feature of the `time` crate, for example by adding the following to your `Cargo.toml`. 52 | 53 | ```toml 54 | time = { version = "0.3", features = ["wasm-bindgen"] } 55 | ``` 56 | 57 | [`tracing-subscriber`]: https://crates.io/crates/tracing-subscriber 58 | [Performance API]: https://developer.mozilla.org/en-US/docs/Web/API/Performance 59 | [`UtcTime`]: https://docs.rs/tracing-subscriber/0.3.18/tracing_subscriber/fmt/time/struct.UtcTime.html 60 | 61 | # License 62 | 63 | This project is dual licensed under the [MIT license] and the [Apache license]. 64 | 65 | [MIT license]: LICENSE-MIT 66 | [Apache license]: LICENSE-APACHE 67 | -------------------------------------------------------------------------------- /examples/trace-yew-app/.gitignore: -------------------------------------------------------------------------------- 1 | /dist 2 | /Cargo.lock 3 | -------------------------------------------------------------------------------- /examples/trace-yew-app/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "trace-yew-app" 3 | version = "0.1.0" 4 | edition = "2021" 5 | publish = false 6 | 7 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 8 | 9 | [dependencies] 10 | yew = { git = "https://github.com/yewstack/yew.git", features = ["csr"] } 11 | tracing = { version = "*", default-features = false } 12 | tracing-subscriber = { version = "*", features = ["time"] } 13 | tracing-web = { path = "../.." } 14 | time = { version = "*", features = ["wasm-bindgen"] } 15 | -------------------------------------------------------------------------------- /examples/trace-yew-app/Trunk.toml: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WorldSEnder/tracing-web/5476b499690d3367e2107b95394ee4779f4ee1aa/examples/trace-yew-app/Trunk.toml -------------------------------------------------------------------------------- /examples/trace-yew-app/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /examples/trace-yew-app/src/main.rs: -------------------------------------------------------------------------------- 1 | use tracing::Span; 2 | use tracing_subscriber::{ 3 | fmt::format::{FmtSpan, Pretty}, 4 | prelude::*, 5 | }; 6 | use yew::{function_component, html, Html}; 7 | 8 | #[function_component] 9 | fn App() -> Html { 10 | html! { 11 |
12 |

{"This web app shows timings of components and tracing with tracing-web"}

13 |
14 | } 15 | } 16 | 17 | fn main() { 18 | let fmt_layer = tracing_subscriber::fmt::layer() 19 | .with_ansi(false) 20 | .without_time() 21 | .with_writer(tracing_web::MakeWebConsoleWriter::new().with_pretty_level()) 22 | .with_level(false) 23 | .with_span_events(FmtSpan::ACTIVE); 24 | let perf_layer = tracing_web::performance_layer().with_details_from_fields(Pretty::default()); 25 | 26 | tracing_subscriber::registry() 27 | .with(fmt_layer) 28 | .with(perf_layer) 29 | .init(); 30 | 31 | tracing::debug_span!("top-level", i = 5).in_scope(|| { 32 | tracing::trace!("This is a trace message."); 33 | let message = "debug message"; 34 | tracing::debug!(msg = ?message, "Hello, world!"); 35 | tracing::warn!("This is a sample warning."); 36 | tracing::error!("This shows up as an error."); 37 | tracing::info!("This contains an informational message."); 38 | Span::current().record("i", 7); 39 | }); 40 | yew::Renderer::::new().render(); 41 | } 42 | -------------------------------------------------------------------------------- /rustfmt.toml: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/WorldSEnder/tracing-web/5476b499690d3367e2107b95394ee4779f4ee1aa/rustfmt.toml -------------------------------------------------------------------------------- /src/console_writer.rs: -------------------------------------------------------------------------------- 1 | use std::io::Write; 2 | 3 | use tracing_core::Level; 4 | use tracing_subscriber::fmt::MakeWriter; 5 | use wasm_bindgen::JsValue; 6 | use web_sys::console; 7 | 8 | /// **Discouraged** A [`MakeWriter`] emitting the written text to the [`console`]. 9 | /// 10 | /// The used log method is sensitive to the level the event is emitted with. 11 | /// 12 | /// | Level | Method | 13 | /// |-----------|------------------| 14 | /// | TRACE | console.debug | 15 | /// | DEBUG | console.debug | 16 | /// | INFO | console.info | 17 | /// | WARN | console.warn | 18 | /// | ERROR | console.error | 19 | /// | other | console.log | 20 | /// 21 | /// ### Note 22 | /// 23 | /// Since version `0.1.3`, you should prefer the alternative, more powerful [`MakeWebConsoleWriter`]. 24 | // For now, I have decided against deprecating this. While I do intend to deprecate or even remove it in 0.2, a warning is probably too picky on downstream developers. 25 | // #[deprecated( 26 | // since = "0.1.3", 27 | // note = "use `MakeWebConsoleWriter` instead, which provides a more future proof API" 28 | // )] 29 | pub struct MakeConsoleWriter; 30 | 31 | /// A [`MakeWriter`] emitting the written text to the [`console`]. 32 | /// 33 | /// The used log method is sensitive to the level the event is emitted with. 34 | /// 35 | /// | Level | Method | 36 | /// |-----------|------------------| 37 | /// | TRACE | console.debug | 38 | /// | DEBUG | console.debug | 39 | /// | INFO | console.info | 40 | /// | WARN | console.warn | 41 | /// | ERROR | console.error | 42 | /// | other | console.log | 43 | pub struct MakeWebConsoleWriter { 44 | use_pretty_label: bool, 45 | } 46 | 47 | impl Default for MakeWebConsoleWriter { 48 | fn default() -> Self { 49 | Self::new() 50 | } 51 | } 52 | 53 | impl MakeWebConsoleWriter { 54 | /// Create a default console writer, i.e. no level annotation is shown when logging a message. 55 | pub fn new() -> Self { 56 | Self { 57 | use_pretty_label: false, 58 | } 59 | } 60 | /// Enables an additional label for the log level to be shown. 61 | /// 62 | /// It is recommended that you also use [`Layer::with_level(false)`] if you use this option, to avoid the event level being shown twice. 63 | /// 64 | /// [`Layer::with_level(false)`]: tracing_subscriber::fmt::Layer::with_level 65 | pub fn with_pretty_level(mut self) -> Self { 66 | self.use_pretty_label = true; 67 | self 68 | } 69 | } 70 | 71 | type LogDispatcher = fn(Level, &str); 72 | 73 | /// Concrete [`std::io::Write`] implementation returned by [`MakeConsoleWriter`] and [`MakeWebConsoleWriter`]. 74 | pub struct ConsoleWriter { 75 | buffer: Vec, 76 | level: Level, 77 | log: LogDispatcher, 78 | } 79 | 80 | impl Write for ConsoleWriter { 81 | fn write(&mut self, buf: &[u8]) -> std::io::Result { 82 | self.buffer.write(buf) 83 | } 84 | 85 | fn flush(&mut self) -> std::io::Result<()> { 86 | // Nothing to-do here, we instead flush on drop 87 | Ok(()) 88 | } 89 | } 90 | 91 | impl Drop for ConsoleWriter { 92 | fn drop(&mut self) { 93 | // TODO: it's rather pointless to decoded to utf-8 here, 94 | // just to re-encode as utf-16 when crossing wasm-bindgen boundaries 95 | // we could use TextDecoder directly to produce a 96 | let message = String::from_utf8_lossy(&self.buffer); 97 | (self.log)(self.level, message.as_ref()) 98 | } 99 | } 100 | 101 | // Now, for the implementation details. For each supported log level, we have a dummy type with a trait impl providing 102 | // the (1) "simple" logging via the console.* methods, just forwarding the message and (2) "pretty" logging which passes 103 | // additional CSS along. The trait makes it convenient to instantiate a generic parameter below to obtain the needed 104 | // fn pointers for the applicable dispatcher. 105 | 106 | trait LogImpl { 107 | fn log_simple(level: Level, msg: &str); 108 | fn log_pretty(level: Level, msg: &str); 109 | } 110 | 111 | const MESSAGE_STYLE: &str = "background: inherit; color: inherit;"; 112 | macro_rules! make_log_impl { 113 | ($T:ident { 114 | simple: $s:expr, 115 | pretty: { 116 | log: $p:expr, fmt: $f:expr, label_style: $l:expr $(,)? 117 | } $(,)? 118 | }) => { 119 | struct $T; 120 | impl LogImpl for $T { 121 | #[inline(always)] 122 | fn log_simple(_level: Level, msg: &str) { 123 | $s(&JsValue::from(msg)); 124 | } 125 | #[inline(always)] 126 | fn log_pretty(_level: Level, msg: &str) { 127 | let fmt = JsValue::from(wasm_bindgen::intern($f)); 128 | let label_style = JsValue::from(wasm_bindgen::intern($l)); 129 | let msg_style = JsValue::from(wasm_bindgen::intern(MESSAGE_STYLE)); 130 | $p(&fmt, &label_style, &msg_style, &JsValue::from(msg)); 131 | } 132 | } 133 | }; 134 | } 135 | 136 | // Even though console.trace exists and generates stack traces, it logs with level: info, so leads to verbose logs, so log with debug 137 | make_log_impl!(LogLevelTrace { simple: console::debug_1, pretty: { log: console::debug_4, fmt: "%cTRACE%c %s", label_style: "color: white; font-weight: bold; padding: 0 5px; background: #75507B;" } }); 138 | make_log_impl!(LogLevelDebug { simple: console::debug_1, pretty: { log: console::debug_4, fmt: "%cDEBUG%c %s", label_style: "color: white; font-weight: bold; padding: 0 5px; background: #3465A4;" } }); 139 | make_log_impl!(LogLevelInfo { simple: console::info_1, pretty: { log: console::info_4, fmt: "%c INFO%c %s", label_style: "color: white; font-weight: bold; padding: 0 5px; background: #4E9A06;" } }); 140 | make_log_impl!(LogLevelWarn { simple: console::warn_1, pretty: { log: console::warn_4, fmt: "%c WARN%c %s", label_style: "color: white; font-weight: bold; padding: 0 5px; background: #C4A000;" } }); 141 | make_log_impl!(LogLevelError { simple: console::error_1, pretty: { log: console::error_4, fmt: "%cERROR%c %s", label_style: "color: white; font-weight: bold; padding: 0 5px; background: #CC0000;" } }); 142 | 143 | // This impl serves as a fallback for potential additions to tracing's levels that I can't forsee. It should not be reachable in code as of the time of writing, but might be in future additions to tracing. 144 | struct LogLevelFallback; 145 | impl LogImpl for LogLevelFallback { 146 | #[inline(always)] 147 | fn log_simple(_level: Level, msg: &str) { 148 | console::log_1(&JsValue::from(msg)) 149 | } 150 | 151 | #[inline(always)] 152 | fn log_pretty(level: Level, msg: &str) { 153 | let fmt = JsValue::from(wasm_bindgen::intern("%c%s%c %s")); 154 | let label_level = JsValue::from(format!("{}", level)); 155 | // Note: `text-transform` might not have perfect browser support, but is available in at least Firefox and Chrome at the time of writing 156 | let label_style = JsValue::from(wasm_bindgen::intern( 157 | "color: white; font-weight: bold; padding: 0 5px; background: #424242; text-transform: uppercase;", 158 | )); 159 | let msg_style = JsValue::from(wasm_bindgen::intern(MESSAGE_STYLE)); 160 | let msg = JsValue::from(msg); 161 | console::log_5(&fmt, &label_style, &label_level, &msg_style, &msg) 162 | } 163 | } 164 | 165 | // An additional trait (implemented again by dummy types) makes it convenient to select the correct 166 | // logging implementation. We can then generalize in `select_dispatcher`. 167 | 168 | trait LogImplStyle { 169 | fn get_dispatch(&self) -> LogDispatcher; 170 | } 171 | struct SimpleStyle; 172 | impl LogImplStyle for SimpleStyle { 173 | #[inline(always)] 174 | fn get_dispatch(&self) -> LogDispatcher { 175 | L::log_simple 176 | } 177 | } 178 | struct PrettyStyle; 179 | impl LogImplStyle for PrettyStyle { 180 | #[inline(always)] 181 | fn get_dispatch(&self) -> LogDispatcher { 182 | L::log_pretty 183 | } 184 | } 185 | 186 | fn select_dispatcher(style: impl LogImplStyle, level: Level) -> LogDispatcher { 187 | if level == Level::TRACE { 188 | style.get_dispatch::() 189 | } else if level == Level::DEBUG { 190 | style.get_dispatch::() 191 | } else if level == Level::INFO { 192 | style.get_dispatch::() 193 | } else if level == Level::WARN { 194 | style.get_dispatch::() 195 | } else if level == Level::ERROR { 196 | style.get_dispatch::() 197 | } else { 198 | style.get_dispatch::() 199 | } 200 | } 201 | 202 | impl MakeConsoleWriter { 203 | // "upgrade" to a MakeWebConsoleWriter, mainly to unify code paths. 204 | fn upgrade(&self) -> MakeWebConsoleWriter { 205 | MakeWebConsoleWriter { 206 | use_pretty_label: false, 207 | } 208 | } 209 | } 210 | impl<'a> MakeWriter<'a> for MakeConsoleWriter { 211 | type Writer = ConsoleWriter; 212 | 213 | fn make_writer(&'a self) -> Self::Writer { 214 | self.upgrade().make_writer() 215 | } 216 | 217 | fn make_writer_for(&'a self, meta: &tracing_core::Metadata<'_>) -> Self::Writer { 218 | self.upgrade().make_writer_for(meta) 219 | } 220 | } 221 | 222 | impl<'a> MakeWriter<'a> for MakeWebConsoleWriter { 223 | type Writer = ConsoleWriter; 224 | 225 | fn make_writer(&'a self) -> Self::Writer { 226 | ConsoleWriter { 227 | buffer: vec![], 228 | level: Level::TRACE, // if no level is known, assume the most detailed 229 | log: if self.use_pretty_label { 230 | PrettyStyle.get_dispatch::() 231 | } else { 232 | SimpleStyle.get_dispatch::() 233 | }, 234 | } 235 | } 236 | 237 | fn make_writer_for(&'a self, meta: &tracing_core::Metadata<'_>) -> Self::Writer { 238 | let level = *meta.level(); 239 | let log_fn = if self.use_pretty_label { 240 | select_dispatcher(PrettyStyle, level) 241 | } else { 242 | select_dispatcher(SimpleStyle, level) 243 | }; 244 | ConsoleWriter { 245 | buffer: vec![], 246 | level, 247 | log: log_fn, 248 | } 249 | } 250 | } 251 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! A tracing compatible subscriber layer for web platforms. 2 | //! 3 | //! # Example usage 4 | //! 5 | //! ```rust, no_run 6 | //! use tracing_web::{MakeWebConsoleWriter, performance_layer}; 7 | //! use tracing_subscriber::fmt::format::Pretty; 8 | //! use tracing_subscriber::fmt::time::UtcTime; 9 | //! use tracing_subscriber::prelude::*; 10 | //! 11 | //! let fmt_layer = tracing_subscriber::fmt::layer() 12 | //! .with_ansi(false) // Only partially supported across browsers 13 | //! .without_time() // std::time is not available in browsers 14 | //! .with_writer(MakeWebConsoleWriter::new()); // write events to the console 15 | //! let perf_layer = performance_layer().with_details_from_fields(Pretty::default()); 16 | //! 17 | //! tracing_subscriber::registry() 18 | //! .with(fmt_layer) 19 | //! .with(perf_layer) 20 | //! .init(); 21 | //! ``` 22 | 23 | #![deny( 24 | missing_docs, 25 | bare_trait_objects, 26 | anonymous_parameters, 27 | elided_lifetimes_in_paths 28 | )] 29 | 30 | mod performance_layer; 31 | pub use performance_layer::{ 32 | performance_layer, FormatSpan, FormatSpanFromFields, PerformanceEventsLayer, 33 | }; 34 | mod console_writer; 35 | pub use console_writer::{ConsoleWriter, MakeConsoleWriter, MakeWebConsoleWriter}; 36 | -------------------------------------------------------------------------------- /src/performance_layer.rs: -------------------------------------------------------------------------------- 1 | use std::marker::PhantomData; 2 | 3 | use js_sys::{JsString, Object, Reflect}; 4 | use tracing_core::{span, Subscriber}; 5 | use tracing_subscriber::{ 6 | field::RecordFields, 7 | fmt::{FormatFields, FormattedFields}, 8 | layer::Context, 9 | registry::{Extensions, ExtensionsMut, LookupSpan, SpanRef}, 10 | Layer, 11 | }; 12 | use wasm_bindgen::{prelude::wasm_bindgen, JsCast, JsValue}; 13 | 14 | #[wasm_bindgen] 15 | extern "C" { 16 | #[wasm_bindgen(js_name = _fakeGlobal)] 17 | type Global; 18 | #[wasm_bindgen()] 19 | type Performance; 20 | #[wasm_bindgen(static_method_of = Global, js_class = "globalThis", getter)] 21 | fn performance() -> Performance; 22 | #[wasm_bindgen(method, catch, js_name = "mark")] 23 | fn do_mark(this: &Performance, name: &str) -> Result<(), JsValue>; 24 | #[wasm_bindgen(method, catch, js_name = "mark")] 25 | fn do_mark_with_details( 26 | this: &Performance, 27 | name: &str, 28 | details: &JsValue, 29 | ) -> Result<(), JsValue>; 30 | #[wasm_bindgen(method, catch, js_name = "measure")] 31 | fn do_measure_with_start_mark_and_end_mark( 32 | this: &Performance, 33 | name: &str, 34 | start: &str, 35 | end: &str, 36 | ) -> Result<(), JsValue>; 37 | #[wasm_bindgen(method, catch, js_name = "measure")] 38 | fn do_measure_with_details( 39 | this: &Performance, 40 | name: &str, 41 | details: &JsValue, 42 | ) -> Result<(), JsValue>; 43 | } 44 | 45 | impl Performance { 46 | fn mark(&self, name: &str) -> Result<(), JsValue> { 47 | self.do_mark(name) 48 | } 49 | fn mark_detailed(&self, name: &str, details: &str) -> Result<(), JsValue> { 50 | let details_obj = Object::create(JsValue::NULL.unchecked_ref::()); 51 | let detail_prop = JsString::from(wasm_bindgen::intern("detail")); 52 | Reflect::set(&details_obj, &detail_prop, &JsValue::from(details)).unwrap(); 53 | self.do_mark_with_details(name, &details_obj) 54 | } 55 | fn measure(&self, name: &str, start: &str, end: &str) -> Result<(), JsValue> { 56 | self.do_measure_with_start_mark_and_end_mark(name, start, end) 57 | } 58 | fn measure_detailed( 59 | &self, 60 | name: &str, 61 | start: &str, 62 | end: &str, 63 | details: &str, 64 | ) -> Result<(), JsValue> { 65 | let details_obj = Object::create(JsValue::NULL.unchecked_ref::()); 66 | let detail_prop = JsString::from(wasm_bindgen::intern("detail")); 67 | let start_prop = JsString::from(wasm_bindgen::intern("start")); 68 | let end_prop = JsString::from(wasm_bindgen::intern("end")); 69 | Reflect::set(&details_obj, &detail_prop, &JsValue::from(details)).unwrap(); 70 | Reflect::set(&details_obj, &start_prop, &JsValue::from(start)).unwrap(); 71 | Reflect::set(&details_obj, &end_prop, &JsValue::from(end)).unwrap(); 72 | self.do_measure_with_details(name, &details_obj) 73 | } 74 | } 75 | 76 | thread_local! { 77 | static PERF: Performance = { 78 | let performance = Global::performance(); 79 | assert!(!performance.is_undefined(), "browser seems to not support the Performance API"); 80 | performance 81 | }; 82 | } 83 | 84 | /// A [`Layer`] that emits span enter, exit and events as [`performance`] marks. 85 | /// 86 | /// [`performance`]: https://developer.mozilla.org/en-US/docs/Web/API/Performance 87 | pub struct PerformanceEventsLayer { 88 | fmt_details: N, 89 | _inner: PhantomData, 90 | } 91 | 92 | impl PerformanceEventsLayer { 93 | /// Change the way additional details are attached to performance events. 94 | /// 95 | /// The given [`FormatFields`] is used to format a string that is attached to each event. 96 | /// See the [`mod@tracing_subscriber::fmt::format`] module for an assortment of available formatters. 97 | pub fn with_details_from_fields( 98 | self, 99 | fmt_fields: N2, 100 | ) -> PerformanceEventsLayer> 101 | where 102 | N2: 'static + for<'writer> FormatFields<'writer>, 103 | { 104 | self.with_details(FormatSpanFromFields { inner: fmt_fields }) 105 | } 106 | /// Change the way additional details are attached to performance events. 107 | /// 108 | /// See also [`with_details_from_fields`](Self::with_details_from_fields) for compatibility with [`mod@tracing_subscriber::fmt::format`]. 109 | pub fn with_details(self, fmt_details: N2) -> PerformanceEventsLayer { 110 | PerformanceEventsLayer { 111 | fmt_details, 112 | _inner: PhantomData, 113 | } 114 | } 115 | } 116 | 117 | impl PerformanceEventsLayer 118 | where 119 | S: Subscriber + for<'lookup> LookupSpan<'lookup>, 120 | N: FormatSpan, 121 | { 122 | fn template_name(span: &SpanRef<'_, S>, event_name: &str) -> String { 123 | let span_id = span.id().into_u64(); 124 | let name = span.metadata().name(); 125 | format!("{name} [{span_id}]: {event_name}") 126 | } 127 | fn span_enter_name(&self, span: &SpanRef<'_, S>) -> String { 128 | Self::template_name(span, "span-enter") 129 | } 130 | fn span_exit_name(&self, span: &SpanRef<'_, S>) -> String { 131 | Self::template_name(span, "span-exit") 132 | } 133 | fn span_record_name(&self, span: &SpanRef<'_, S>) -> String { 134 | Self::template_name(span, "span-record") 135 | } 136 | fn span_measure_name(&self, span: &SpanRef<'_, S>) -> String { 137 | Self::template_name(span, "span-measure") 138 | } 139 | } 140 | 141 | impl Layer for PerformanceEventsLayer 142 | where 143 | S: Subscriber + for<'lookup> LookupSpan<'lookup>, 144 | N: FormatSpan, 145 | { 146 | fn on_new_span(&self, attrs: &span::Attributes<'_>, span: &span::Id, ctx: Context<'_, S>) { 147 | let span = ctx.span(span).expect("can't find span, this is a bug"); 148 | 149 | self.fmt_details 150 | .add_details(&mut span.extensions_mut(), attrs); 151 | } 152 | fn on_record(&self, span: &span::Id, values: &span::Record<'_>, ctx: Context<'_, S>) { 153 | let span = ctx.span(span).expect("can't find span, this is a bug"); 154 | self.fmt_details 155 | .record_values(&mut span.extensions_mut(), values); 156 | 157 | let mark_name = self.span_record_name(&span); 158 | let _ = PERF.with(|p| { 159 | if let Some(details) = self.fmt_details.find_details(&span.extensions()) { 160 | p.mark_detailed(&mark_name, details) 161 | } else { 162 | p.mark(&mark_name) 163 | } 164 | }); // Ignore errors 165 | } 166 | fn on_enter(&self, span: &span::Id, ctx: Context<'_, S>) { 167 | let span = ctx.span(span).expect("can't find span, this is a bug"); 168 | let mark_name = self.span_enter_name(&span); 169 | let _ = PERF.with(|p| { 170 | if let Some(details) = self.fmt_details.find_details(&span.extensions()) { 171 | p.mark_detailed(&mark_name, details) 172 | } else { 173 | p.mark(&mark_name) 174 | } 175 | }); // Ignore errors 176 | } 177 | fn on_exit(&self, span: &span::Id, ctx: Context<'_, S>) { 178 | let span = ctx.span(span).expect("can't find span, this is a bug"); 179 | let mark_enter_name = self.span_enter_name(&span); 180 | let mark_exit_name = self.span_exit_name(&span); 181 | let mark_measure_name = self.span_measure_name(&span); 182 | let _ = PERF.with(|p| { 183 | if let Some(details) = self.fmt_details.find_details(&span.extensions()) { 184 | p.mark_detailed(&mark_exit_name, details)?; 185 | p.measure_detailed( 186 | &mark_measure_name, 187 | &mark_enter_name, 188 | &mark_exit_name, 189 | details, 190 | )?; 191 | } else { 192 | p.mark(&mark_exit_name)?; 193 | p.measure(&mark_measure_name, &mark_enter_name, &mark_exit_name)?; 194 | } 195 | Result::<(), JsValue>::Ok(()) 196 | }); // Ignore errors 197 | } 198 | fn on_id_change(&self, _: &span::Id, _: &span::Id, _ctx: Context<'_, S>) { 199 | web_sys::console::warn_1(&JsValue::from( 200 | "A span changed id, this is currently not supported", 201 | )); 202 | debug_assert!(false, "A span changed id, this is currently not supported"); 203 | } 204 | } 205 | 206 | /// Construct a new layer recording performance events. 207 | /// 208 | /// The default will not attach any additional field information to the events. 209 | pub fn performance_layer() -> PerformanceEventsLayer 210 | where 211 | S: Subscriber + for<'lookup> LookupSpan<'lookup>, 212 | { 213 | PerformanceEventsLayer { 214 | fmt_details: (), 215 | _inner: PhantomData, 216 | } 217 | } 218 | 219 | /// Determine what additional information will be attached to the performance events. 220 | pub trait FormatSpan: 'static { 221 | /// Find the details in the extensions of a span that will be recorded with the event. 222 | fn find_details<'ext>(&self, ext: &'ext Extensions<'_>) -> Option<&'ext str>; 223 | /// Called when a span is constructed, with its initial attributes. 224 | /// 225 | /// This method should insert, for later consumption in [`Self::find_details`], a description of the details. 226 | fn add_details(&self, ext: &mut ExtensionsMut<'_>, attrs: &span::Attributes<'_>); 227 | /// Called when a span records some values. 228 | /// 229 | /// This method should modify, for later consumption in [`Self::find_details`], the description of the details. 230 | fn record_values(&self, ext: &mut ExtensionsMut<'_>, values: &span::Record<'_>); 231 | } 232 | 233 | impl FormatSpan for () { 234 | fn find_details<'ext>(&self, _: &'ext Extensions<'_>) -> Option<&'ext str> { 235 | None 236 | } 237 | fn add_details(&self, _: &mut ExtensionsMut<'_>, _: &span::Attributes<'_>) {} 238 | fn record_values(&self, _: &mut ExtensionsMut<'_>, _: &span::Record<'_>) {} 239 | } 240 | 241 | /// An adaptor for Formatters from [`mod@tracing_subscriber::fmt::format`] as a [`FormatSpan`]. 242 | /// 243 | /// Uses [`FormattedFields`] to store the details attachement, so it might reuse an existing extension 244 | /// for logging, to save some work visiting the recorded fields. 245 | pub struct FormatSpanFromFields { 246 | inner: N, 247 | } 248 | impl FormatSpanFromFields 249 | where 250 | N: 'static + for<'writer> FormatFields<'writer>, 251 | { 252 | fn add_formatted_fields(&self, ext: &mut ExtensionsMut<'_>, fields: impl RecordFields) { 253 | if ext.get_mut::>().is_none() { 254 | let mut fmt_fields = FormattedFields::::new(String::new()); 255 | if self 256 | .inner 257 | .format_fields(fmt_fields.as_writer(), fields) 258 | .is_ok() 259 | { 260 | ext.insert(fmt_fields); 261 | } 262 | } 263 | } 264 | } 265 | 266 | impl FormatSpan for FormatSpanFromFields 267 | where 268 | N: 'static + for<'writer> FormatFields<'writer>, 269 | { 270 | fn find_details<'ext>(&self, ext: &'ext Extensions<'_>) -> Option<&'ext str> { 271 | let fields = ext.get::>()?; 272 | Some(&fields.fields) 273 | } 274 | 275 | fn add_details(&self, ext: &mut ExtensionsMut<'_>, attrs: &span::Attributes<'_>) { 276 | self.add_formatted_fields(ext, attrs); 277 | } 278 | 279 | fn record_values(&self, ext: &mut ExtensionsMut<'_>, values: &span::Record<'_>) { 280 | if let Some(fields) = ext.get_mut::>() { 281 | let _ = self.inner.add_fields(fields, values); 282 | } else { 283 | self.add_formatted_fields(ext, values); 284 | } 285 | } 286 | } 287 | --------------------------------------------------------------------------------