]>
Commit | Line | Data |
---|---|---|
a2a8927a XL |
1 | //! This crate allows tools to enable rust logging without having to magically |
2 | //! match rustc's tracing crate version. | |
3 | //! | |
4 | //! For example if someone is working on rustc_ast and wants to write some | |
5 | //! minimal code against it to run in a debugger, with access to the `debug!` | |
6 | //! logs emitted by rustc_ast, that can be done by writing: | |
7 | //! | |
8 | //! ```toml | |
9 | //! [dependencies] | |
10 | //! rustc_ast = { path = "../rust/compiler/rustc_ast" } | |
11 | //! rustc_log = { path = "../rust/compiler/rustc_log" } | |
12 | //! rustc_span = { path = "../rust/compiler/rustc_span" } | |
13 | //! ``` | |
14 | //! | |
15 | //! ``` | |
16 | //! fn main() { | |
9ffffee4 | 17 | //! rustc_log::init_env_logger("LOG").unwrap(); |
a2a8927a XL |
18 | //! |
19 | //! let edition = rustc_span::edition::Edition::Edition2021; | |
20 | //! rustc_span::create_session_globals_then(edition, || { | |
21 | //! /* ... */ | |
22 | //! }); | |
23 | //! } | |
24 | //! ``` | |
25 | //! | |
9ffffee4 | 26 | //! Now `LOG=debug cargo run` will run your minimal main.rs and show |
a2a8927a | 27 | //! rustc's debug logging. In a workflow like this, one might also add |
9ffffee4 | 28 | //! `std::env::set_var("LOG", "debug")` to the top of main so that `cargo |
a2a8927a XL |
29 | //! run` by itself is sufficient to get logs. |
30 | //! | |
31 | //! The reason rustc_log is a tiny separate crate, as opposed to exposing the | |
32 | //! same things in rustc_driver only, is to enable the above workflow. If you | |
33 | //! had to depend on rustc_driver in order to turn on rustc's debug logs, that's | |
34 | //! an enormously bigger dependency tree; every change you make to rustc_ast (or | |
35 | //! whichever piece of the compiler you are interested in) would involve | |
36 | //! rebuilding all the rest of rustc up to rustc_driver in order to run your | |
37 | //! main.rs. Whereas by depending only on rustc_log and the few crates you are | |
38 | //! debugging, you can make changes inside those crates and quickly run main.rs | |
39 | //! to read the debug logs. | |
40 | ||
f2b60f7d FG |
41 | #![deny(rustc::untranslatable_diagnostic)] |
42 | #![deny(rustc::diagnostic_outside_of_impl)] | |
487cf647 | 43 | #![feature(is_terminal)] |
f2b60f7d | 44 | |
a2a8927a XL |
45 | use std::env::{self, VarError}; |
46 | use std::fmt::{self, Display}; | |
487cf647 | 47 | use std::io::{self, IsTerminal}; |
9c376795 | 48 | use tracing_core::{Event, Subscriber}; |
a2a8927a | 49 | use tracing_subscriber::filter::{Directive, EnvFilter, LevelFilter}; |
9c376795 FG |
50 | use tracing_subscriber::fmt::{ |
51 | format::{self, FormatEvent, FormatFields}, | |
52 | FmtContext, | |
53 | }; | |
a2a8927a XL |
54 | use tracing_subscriber::layer::SubscriberExt; |
55 | ||
a2a8927a XL |
56 | pub fn init_env_logger(env: &str) -> Result<(), Error> { |
57 | let filter = match env::var(env) { | |
58 | Ok(env) => EnvFilter::new(env), | |
59 | _ => EnvFilter::default().add_directive(Directive::from(LevelFilter::WARN)), | |
60 | }; | |
61 | ||
62 | let color_logs = match env::var(String::from(env) + "_COLOR") { | |
63 | Ok(value) => match value.as_ref() { | |
64 | "always" => true, | |
65 | "never" => false, | |
66 | "auto" => stderr_isatty(), | |
67 | _ => return Err(Error::InvalidColorValue(value)), | |
68 | }, | |
69 | Err(VarError::NotPresent) => stderr_isatty(), | |
70 | Err(VarError::NotUnicode(_value)) => return Err(Error::NonUnicodeColorValue), | |
71 | }; | |
72 | ||
04454e1e FG |
73 | let verbose_entry_exit = match env::var_os(String::from(env) + "_ENTRY_EXIT") { |
74 | None => false, | |
923072b8 | 75 | Some(v) => &v != "0", |
04454e1e FG |
76 | }; |
77 | ||
a2a8927a XL |
78 | let layer = tracing_tree::HierarchicalLayer::default() |
79 | .with_writer(io::stderr) | |
80 | .with_indent_lines(true) | |
81 | .with_ansi(color_logs) | |
82 | .with_targets(true) | |
04454e1e FG |
83 | .with_verbose_exit(verbose_entry_exit) |
84 | .with_verbose_entry(verbose_entry_exit) | |
a2a8927a XL |
85 | .with_indent_amount(2); |
86 | #[cfg(parallel_compiler)] | |
87 | let layer = layer.with_thread_ids(true).with_thread_names(true); | |
88 | ||
89 | let subscriber = tracing_subscriber::Registry::default().with(filter).with(layer); | |
9ffffee4 FG |
90 | match env::var(format!("{env}_BACKTRACE")) { |
91 | Ok(str) => { | |
9c376795 FG |
92 | let fmt_layer = tracing_subscriber::fmt::layer() |
93 | .with_writer(io::stderr) | |
94 | .without_time() | |
9ffffee4 | 95 | .event_format(BacktraceFormatter { backtrace_target: str }); |
9c376795 FG |
96 | let subscriber = subscriber.with(fmt_layer); |
97 | tracing::subscriber::set_global_default(subscriber).unwrap(); | |
98 | } | |
9ffffee4 | 99 | Err(_) => { |
9c376795 FG |
100 | tracing::subscriber::set_global_default(subscriber).unwrap(); |
101 | } | |
102 | }; | |
a2a8927a XL |
103 | |
104 | Ok(()) | |
105 | } | |
106 | ||
9c376795 FG |
107 | struct BacktraceFormatter { |
108 | backtrace_target: String, | |
109 | } | |
110 | ||
111 | impl<S, N> FormatEvent<S, N> for BacktraceFormatter | |
112 | where | |
113 | S: Subscriber + for<'a> tracing_subscriber::registry::LookupSpan<'a>, | |
114 | N: for<'a> FormatFields<'a> + 'static, | |
115 | { | |
116 | fn format_event( | |
117 | &self, | |
118 | _ctx: &FmtContext<'_, S, N>, | |
119 | mut writer: format::Writer<'_>, | |
120 | event: &Event<'_>, | |
121 | ) -> fmt::Result { | |
122 | let target = event.metadata().target(); | |
123 | if !target.contains(&self.backtrace_target) { | |
124 | return Ok(()); | |
125 | } | |
126 | let backtrace = std::backtrace::Backtrace::capture(); | |
127 | writeln!(writer, "stack backtrace: \n{:?}", backtrace) | |
128 | } | |
129 | } | |
130 | ||
a2a8927a | 131 | pub fn stdout_isatty() -> bool { |
487cf647 | 132 | io::stdout().is_terminal() |
a2a8927a XL |
133 | } |
134 | ||
135 | pub fn stderr_isatty() -> bool { | |
487cf647 | 136 | io::stderr().is_terminal() |
a2a8927a XL |
137 | } |
138 | ||
139 | #[derive(Debug)] | |
140 | pub enum Error { | |
141 | InvalidColorValue(String), | |
142 | NonUnicodeColorValue, | |
143 | } | |
144 | ||
145 | impl std::error::Error for Error {} | |
146 | ||
147 | impl Display for Error { | |
148 | fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { | |
149 | match self { | |
150 | Error::InvalidColorValue(value) => write!( | |
151 | formatter, | |
9c376795 | 152 | "invalid log color value '{value}': expected one of always, never, or auto", |
a2a8927a XL |
153 | ), |
154 | Error::NonUnicodeColorValue => write!( | |
155 | formatter, | |
156 | "non-Unicode log color value: expected one of always, never, or auto", | |
157 | ), | |
158 | } | |
159 | } | |
160 | } |