midenc_log/lib.rs
1//! A configurable logger that can be configured both directly and via environment variables.
2//!
3//! Designed for use with [`log`](log-crate-url).
4//!
5//! This crate is inspired by [`midenc_log`](https://crates.io/crates/midenc_log), but provides
6//! additional features specific to the Miden compiler that make it more useful when diagnosing
7//! issues in a pipeline that has an enormous quantity of verbose trace logs that are emitted for
8//! a large number of different entities in the compilation graph. Typically, we're interested in
9//! output related to a specific function, possibly refined to specific components of the compiler,
10//! or even specific areas of those components.
11//!
12//! There are a few primary use cases we're interested in supporting with this crate:
13//!
14//! 1. Emit all logs at a given log level, e.g. `MIDENC_TRACE=trace cargo miden build`
15//! 2. Same as 1, but for a specific component of the compiler, e.g. `MIDENC_TRACE=codegen=trace`
16//! 3. Same as 2, but for a specific topic within that component, e.g.
17//! `MIDENC_TRACE=pass:cse=trace`
18//! 4. Same as 2, but for any topic in that component which matches a regular expression, e.g.
19//! `MIDENC_TRACE=pass:.*=trace`
20//! 5. Any of the above, but only for an operation which matches a given filter:
21//! a. Match any op that implements Symbol, e.g. `MIDENC_TRACE=trace MIDENC_TRACE_FILTER=symbol:*`
22//! b. Match a symbol whose name matches a regular expression, e.g. `MIDENC_TRACE=trace MIDENC_TRACE_FILTER=symbol:foo`
23//! c. Match a specific operation type, e.g. `MIDENC_TRACE=trace MIDENC_TRACE_FILTER=op:hir.function`
24//! 6. Negated filters, e.g. emit all logs which match any positive filters and are not also matched
25//! by the negative filter, e.g.:
26//! a. Emit everything except logs for the "dataflow" component: `MIDENC_TRACE=trace,-dataflow`
27//! b. Emit everything except trace-level logs for the "dataflow" component: `MIDENC_TRACE=trace,-dataflow=trace`
28//! c. Emit logs for the "dataflow" component, except trace-level logs for the "solver" topic: `MIDENC_TRACE=dataflow=trace,-dataflow:solver=trace`
29//!
30//! By default, logs are written to `stderr`, but this is configurable.
31//!
32//! NOTE: The functionality here relies on `log` targets using a structured format that we can
33//! parse and extract the relevant pieces from. Any `log` targets which are not in this format
34//! will be treated as a single component and emitted according to the default logging rules,
35//! while still supporting filtering those components. The format is as follows:
36//!
37//! ```ignore
38//! scope := component (":" topic)*
39//!
40//! component := [A-Za-z0-9_-]+
41//! topic := [^:,=]+
42//! ```
43//!
44//! When there are nested topics, the last topic is considered to contain the relevant symbol for
45//! that log message, and so will be filtered by `MIDENC_TRACE_FILTER`, not any topic patterns in
46//! `MIDENC_TRACE`.
47//!
48//! ## Example
49//!
50//! ```
51//! use log::{debug, error, log_enabled, info, Level};
52//!
53//! midenc_log::init();
54//!
55//! debug!("this is a debug {}", "message");
56//! error!("this is printed by default");
57//!
58//! if log_enabled!(Level::Info) {
59//! let x = 3 * 4; // expensive computation
60//! info!("the answer was: {}", x);
61//! }
62//! ```
63//!
64//! Assumes the binary is `main`:
65//!
66//! ```console
67//! $ RUST_LOG=error ./main
68//! [2017-11-09T02:12:24Z ERROR main] this is printed by default
69//! ```
70//!
71//! ```console
72//! $ RUST_LOG=info ./main
73//! [2017-11-09T02:12:24Z ERROR main] this is printed by default
74//! [2017-11-09T02:12:24Z INFO main] the answer was: 12
75//! ```
76//!
77//! ```console
78//! $ RUST_LOG=debug ./main
79//! [2017-11-09T02:12:24Z DEBUG main] this is a debug message
80//! [2017-11-09T02:12:24Z ERROR main] this is printed by default
81//! [2017-11-09T02:12:24Z INFO main] the answer was: 12
82//! ```
83//!
84//! You can also set the log level on a per module basis:
85//!
86//! ```console
87//! $ RUST_LOG=main=info ./main
88//! [2017-11-09T02:12:24Z ERROR main] this is printed by default
89//! [2017-11-09T02:12:24Z INFO main] the answer was: 12
90//! ```
91//!
92//! And enable all logging:
93//!
94//! ```console
95//! $ RUST_LOG=main ./main
96//! [2017-11-09T02:12:24Z DEBUG main] this is a debug message
97//! [2017-11-09T02:12:24Z ERROR main] this is printed by default
98//! [2017-11-09T02:12:24Z INFO main] the answer was: 12
99//! ```
100//!
101//! If the binary name contains hyphens, you will need to replace
102//! them with underscores:
103//!
104//! ```console
105//! $ RUST_LOG=my_app ./my-app
106//! [2017-11-09T02:12:24Z DEBUG my_app] this is a debug message
107//! [2017-11-09T02:12:24Z ERROR my_app] this is printed by default
108//! [2017-11-09T02:12:24Z INFO my_app] the answer was: 12
109//! ```
110//!
111//! This is because Rust modules and crates cannot contain hyphens
112//! in their name, although `cargo` continues to accept them.
113//!
114//! See the documentation for the [`log` crate][log-crate-url] for more
115//! information about its API.
116//!
117//! ## Enabling logging
118//!
119//! **By default all logging is disabled except for the `error` level**
120//!
121//! The **`RUST_LOG`** environment variable controls logging with the syntax:
122//! ```console
123//! RUST_LOG=[target][=][level][,...]
124//! ```
125//! Or in other words, its a comma-separated list of directives.
126//! Directives can filter by **target**, by **level**, or both (using `=`).
127//!
128//! For example,
129//! ```console
130//! RUST_LOG=data=debug,hardware=debug
131//! ```
132//!
133//! **target** is typically the path of the module the message
134//! in question originated from, though it can be overridden.
135//! The path is rooted in the name of the crate it was compiled for, so if
136//! your program is in a file called, for example, `hello.rs`, the path would
137//! simply be `hello`.
138//!
139//! Furthermore, the log can be filtered using prefix-search based on the
140//! specified log target.
141//!
142//! For example, `RUST_LOG=example` would match the following targets:
143//! - `example`
144//! - `example::test`
145//! - `example::test::module::submodule`
146//! - `examples::and_more_examples`
147//!
148//! When providing the crate name or a module path, explicitly specifying the
149//! log level is optional. If omitted, all logging for the item will be
150//! enabled.
151//!
152//! **level** is the maximum [`log::Level`][level-enum] to be shown and includes:
153//! - `error`
154//! - `warn`
155//! - `info`
156//! - `debug`
157//! - `trace`
158//! - `off` (pseudo level to disable all logging for the target)
159//!
160//! Logging level names are case-insensitive; e.g.,
161//! `debug`, `DEBUG`, and `dEbuG` all represent the same logging level. For
162//! consistency, our convention is to use the lower case names. Where our docs
163//! do use other forms, they do so in the context of specific examples, so you
164//! won't be surprised if you see similar usage in the wild.
165//!
166//! Some examples of valid values of `RUST_LOG` are:
167//!
168//! - `RUST_LOG=hello` turns on all logging for the `hello` module
169//! - `RUST_LOG=trace` turns on all logging for the application, regardless of its name
170//! - `RUST_LOG=TRACE` turns on all logging for the application, regardless of its name (same as previous)
171//! - `RUST_LOG=info` turns on all info logging
172//! - `RUST_LOG=INFO` turns on all info logging (same as previous)
173//! - `RUST_LOG=hello=debug` turns on debug logging for `hello`
174//! - `RUST_LOG=hello=DEBUG` turns on debug logging for `hello` (same as previous)
175//! - `RUST_LOG=hello,std::option` turns on `hello`, and std's option logging
176//! - `RUST_LOG=error,hello=warn` turn on global error logging and also warn for `hello`
177//! - `RUST_LOG=error,hello=off` turn on global error logging, but turn off logging for `hello`
178//! - `RUST_LOG=off` turns off all logging for the application
179//! - `RUST_LOG=OFF` turns off all logging for the application (same as previous)
180//!
181//! ## Filtering results
182//!
183//! A `RUST_LOG` directive may include a regex filter. The syntax is to append `/`
184//! followed by a regex. Each message is checked against the regex, and is only
185//! logged if it matches. Note that the matching is done after formatting the
186//! log string but before adding any logging meta-data. There is a single filter
187//! for all modules.
188//!
189//! Some examples:
190//!
191//! * `hello/foo` turns on all logging for the 'hello' module where the log
192//! message includes 'foo'.
193//! * `info/f.o` turns on all info logging where the log message includes 'foo',
194//! 'f1o', 'fao', etc.
195//! * `hello=debug/foo*foo` turns on debug logging for 'hello' where the log
196//! message includes 'foofoo' or 'fofoo' or 'fooooooofoo', etc.
197//! * `error,hello=warn/[0-9]scopes` turn on global error logging and also
198//! warn for hello. In both cases the log message must include a single digit
199//! number followed by 'scopes'.
200//!
201//! ## Capturing logs in tests
202//!
203//! Records logged during `cargo test` will not be captured by the test harness by default.
204//! The [`Builder::is_test`] method can be used in unit tests to ensure logs will be captured:
205//!
206//! ```test_harness
207//! #[cfg(test)]
208//! mod tests {
209//! use log::info;
210//!
211//! fn init() {
212//! let _ = midenc_log::builder().is_test(true).try_init();
213//! }
214//!
215//! #[test]
216//! fn it_works() {
217//! init();
218//!
219//! info!("This record will be captured by `cargo test`");
220//!
221//! assert_eq!(2, 1 + 1);
222//! }
223//! }
224//! ```
225//!
226//! Enabling test capturing comes at the expense of color and other style support
227//! and may have performance implications.
228//!
229//! ## Colors
230//!
231//! Outputting of colors and other styles can be controlled by the `RUST_LOG_STYLE`
232//! environment variable. It accepts the following [values][fmt::WriteStyle]:
233//!
234//! * `auto` (default) will attempt to print style characters, but don't force the issue.
235//! If the console isn't available on Windows, or if TERM=dumb, for example, then don't print colors.
236//! * `always` will always print style characters even if they aren't supported by the terminal.
237//! This includes emitting ANSI colors on Windows if the console API is unavailable.
238//! * `never` will never print style characters.
239//!
240//! Color may be applied in the logged message or a [custom formatter][fmt].
241//!
242//! <div class="warning">
243//!
244//! Logging of untrusted inputs can cause unexpected behavior as they may include ANSI escape codes which
245//! will be forwarded to the users terminal as part of "Weaponizing ANSI Escape Sequences".
246//!
247//! Mitigations include:
248//! - Setting `RUST_LOG_STYLE=never` to have all ANSI escape codes stripped
249//! - In the application, calling [`Builder::write_style(Never)`][Builder::write_style] to have all ANSI escape codes stripped
250//! - In the application, [stripping ANSI escape codes](https://docs.rs/anstream/latest/anstream/adapter/fn.strip_str.html)
251//! from user inputs
252//!
253//! Note: deactivating the build-time feature `color` is not a mitigation as that removes all ANSI escape code
254//! stripping from `midenc_log`.
255//!
256//! </div>
257//!
258//! ## Tweaking the default format
259//!
260//! Parts of the default format can be excluded from the log output using the [`Builder`].
261//! The following example excludes the timestamp from the log output:
262//!
263//! ```
264//! midenc_log::builder()
265//! .format_timestamp(None)
266//! .init();
267//! ```
268//!
269//! ### Stability of the default format
270//!
271//! The default format won't optimise for long-term stability, and explicitly makes no
272//! guarantees about the stability of its output across major, minor or patch version
273//! bumps during `0.x`.
274//!
275//! If you want to capture or interpret the output of `midenc_log` programmatically
276//! then you should use a custom format.
277//!
278//! ### Using a custom format
279//!
280//! Custom formats can be provided as closures to the [`Builder`].
281//! These closures take a [`Formatter`][crate::fmt::Formatter] and `log::Record` as arguments:
282//!
283//! ```
284//! use std::io::Write;
285//!
286//! midenc_log::builder()
287//! .format(|buf, record| {
288//! writeln!(buf, "{}: {}", record.level(), record.args())
289//! })
290//! .init();
291//! ```
292//!
293//! See the [`fmt`] module for more details about custom formats.
294//!
295//! ## Specifying defaults for environment variables
296//!
297//! `midenc_log` can read configuration from environment variables.
298//! If these variables aren't present, the default value to use can be tweaked with the [`Env`] type.
299//! The following example defaults to log `warn` and above if the `RUST_LOG` environment variable
300//! isn't set:
301//!
302//! ```
303//! use midenc_log::Env;
304//!
305//! midenc_log::Builder::from_env(Env::default().default_filter_or("warn")).init();
306//! ```
307//!
308//! [level-enum]: https://docs.rs/log/latest/log/enum.Level.html
309//! [log-crate-url]: https://docs.rs/log
310
311#![cfg_attr(docsrs, feature(doc_cfg))]
312#![warn(clippy::print_stderr)]
313#![warn(clippy::print_stdout)]
314#![allow(clippy::test_attr_in_doctest)]
315
316pub mod filter;
317mod logger;
318mod writer;
319
320pub mod fmt;
321
322pub use self::{
323 fmt::{Target, TimestampPrecision, WriteStyle},
324 logger::*,
325};
326
327#[doc = include_str!("../README.md")]
328#[cfg(doctest)]
329pub struct ReadmeDoctests;