]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_log/src/lib.rs
fc1cabd2de95134ab892f7e9f06b8b09d90e2fa2
[rust.git] / compiler / rustc_log / src / lib.rs
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() {
17 //!     rustc_log::init_rustc_env_logger().unwrap();
18 //!
19 //!     let edition = rustc_span::edition::Edition::Edition2021;
20 //!     rustc_span::create_session_globals_then(edition, || {
21 //!         /* ... */
22 //!     });
23 //! }
24 //! ```
25 //!
26 //! Now `RUSTC_LOG=debug cargo run` will run your minimal main.rs and show
27 //! rustc's debug logging. In a workflow like this, one might also add
28 //! `std::env::set_var("RUSTC_LOG", "debug")` to the top of main so that `cargo
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
41 #![deny(rustc::untranslatable_diagnostic)]
42 #![deny(rustc::diagnostic_outside_of_impl)]
43 #![feature(is_terminal)]
44
45 use std::env::{self, VarError};
46 use std::fmt::{self, Display};
47 use std::io::{self, IsTerminal};
48 use tracing_core::{Event, Subscriber};
49 use tracing_subscriber::filter::{Directive, EnvFilter, LevelFilter};
50 use tracing_subscriber::fmt::{
51     format::{self, FormatEvent, FormatFields},
52     FmtContext,
53 };
54 use tracing_subscriber::layer::SubscriberExt;
55
56 pub fn init_rustc_env_logger() -> Result<(), Error> {
57     init_rustc_env_logger_with_backtrace_option(&None)
58 }
59
60 pub fn init_rustc_env_logger_with_backtrace_option(
61     backtrace_target: &Option<String>,
62 ) -> Result<(), Error> {
63     init_env_logger_with_backtrace_option("RUSTC_LOG", backtrace_target)
64 }
65
66 /// In contrast to `init_rustc_env_logger` this allows you to choose an env var
67 /// other than `RUSTC_LOG`.
68 pub fn init_env_logger(env: &str) -> Result<(), Error> {
69     init_env_logger_with_backtrace_option(env, &None)
70 }
71
72 pub fn init_env_logger_with_backtrace_option(
73     env: &str,
74     backtrace_target: &Option<String>,
75 ) -> Result<(), Error> {
76     let filter = match env::var(env) {
77         Ok(env) => EnvFilter::new(env),
78         _ => EnvFilter::default().add_directive(Directive::from(LevelFilter::WARN)),
79     };
80
81     let color_logs = match env::var(String::from(env) + "_COLOR") {
82         Ok(value) => match value.as_ref() {
83             "always" => true,
84             "never" => false,
85             "auto" => stderr_isatty(),
86             _ => return Err(Error::InvalidColorValue(value)),
87         },
88         Err(VarError::NotPresent) => stderr_isatty(),
89         Err(VarError::NotUnicode(_value)) => return Err(Error::NonUnicodeColorValue),
90     };
91
92     let verbose_entry_exit = match env::var_os(String::from(env) + "_ENTRY_EXIT") {
93         None => false,
94         Some(v) => &v != "0",
95     };
96
97     let layer = tracing_tree::HierarchicalLayer::default()
98         .with_writer(io::stderr)
99         .with_indent_lines(true)
100         .with_ansi(color_logs)
101         .with_targets(true)
102         .with_verbose_exit(verbose_entry_exit)
103         .with_verbose_entry(verbose_entry_exit)
104         .with_indent_amount(2);
105     #[cfg(parallel_compiler)]
106     let layer = layer.with_thread_ids(true).with_thread_names(true);
107
108     let subscriber = tracing_subscriber::Registry::default().with(filter).with(layer);
109     match backtrace_target {
110         Some(str) => {
111             let fmt_layer = tracing_subscriber::fmt::layer()
112                 .with_writer(io::stderr)
113                 .without_time()
114                 .event_format(BacktraceFormatter { backtrace_target: str.to_string() });
115             let subscriber = subscriber.with(fmt_layer);
116             tracing::subscriber::set_global_default(subscriber).unwrap();
117         }
118         None => {
119             tracing::subscriber::set_global_default(subscriber).unwrap();
120         }
121     };
122
123     Ok(())
124 }
125
126 struct BacktraceFormatter {
127     backtrace_target: String,
128 }
129
130 impl<S, N> FormatEvent<S, N> for BacktraceFormatter
131 where
132     S: Subscriber + for<'a> tracing_subscriber::registry::LookupSpan<'a>,
133     N: for<'a> FormatFields<'a> + 'static,
134 {
135     fn format_event(
136         &self,
137         _ctx: &FmtContext<'_, S, N>,
138         mut writer: format::Writer<'_>,
139         event: &Event<'_>,
140     ) -> fmt::Result {
141         let target = event.metadata().target();
142         if !target.contains(&self.backtrace_target) {
143             return Ok(());
144         }
145         let backtrace = std::backtrace::Backtrace::capture();
146         writeln!(writer, "stack backtrace: \n{:?}", backtrace)
147     }
148 }
149
150 pub fn stdout_isatty() -> bool {
151     io::stdout().is_terminal()
152 }
153
154 pub fn stderr_isatty() -> bool {
155     io::stderr().is_terminal()
156 }
157
158 #[derive(Debug)]
159 pub enum Error {
160     InvalidColorValue(String),
161     NonUnicodeColorValue,
162 }
163
164 impl std::error::Error for Error {}
165
166 impl Display for Error {
167     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
168         match self {
169             Error::InvalidColorValue(value) => write!(
170                 formatter,
171                 "invalid log color value '{value}': expected one of always, never, or auto",
172             ),
173             Error::NonUnicodeColorValue => write!(
174                 formatter,
175                 "non-Unicode log color value: expected one of always, never, or auto",
176             ),
177         }
178     }
179 }