1 // Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! A simple logger configured via environment variables which writes
12 //! to stdout or stderr, for use with the logging facade exposed by the
13 //! [`log` crate][log-crate-url].
18 //! #[macro_use] extern crate log;
19 //! extern crate env_logger;
24 //! env_logger::init();
26 //! debug!("this is a debug {}", "message");
27 //! error!("this is printed by default");
29 //! if log_enabled!(Level::Info) {
30 //! let x = 3 * 4; // expensive computation
31 //! info!("the answer was: {}", x);
36 //! Assumes the binary is `main`:
39 //! $ RUST_LOG=error ./main
40 //! [2017-11-09T02:12:24Z ERROR main] this is printed by default
44 //! $ RUST_LOG=info ./main
45 //! [2017-11-09T02:12:24Z ERROR main] this is printed by default
46 //! [2017-11-09T02:12:24Z INFO main] the answer was: 12
50 //! $ RUST_LOG=debug ./main
51 //! [2017-11-09T02:12:24Z DEBUG main] this is a debug message
52 //! [2017-11-09T02:12:24Z ERROR main] this is printed by default
53 //! [2017-11-09T02:12:24Z INFO main] the answer was: 12
56 //! You can also set the log level on a per module basis:
59 //! $ RUST_LOG=main=info ./main
60 //! [2017-11-09T02:12:24Z ERROR main] this is printed by default
61 //! [2017-11-09T02:12:24Z INFO main] the answer was: 12
64 //! And enable all logging:
67 //! $ RUST_LOG=main ./main
68 //! [2017-11-09T02:12:24Z DEBUG main] this is a debug message
69 //! [2017-11-09T02:12:24Z ERROR main] this is printed by default
70 //! [2017-11-09T02:12:24Z INFO main] the answer was: 12
73 //! If the binary name contains hyphens, you will need to replace
74 //! them with underscores:
77 //! $ RUST_LOG=my_app ./my-app
78 //! [2017-11-09T02:12:24Z DEBUG my_app] this is a debug message
79 //! [2017-11-09T02:12:24Z ERROR my_app] this is printed by default
80 //! [2017-11-09T02:12:24Z INFO my_app] the answer was: 12
83 //! This is because Rust modules and crates cannot contain hyphens
84 //! in their name, although `cargo` continues to accept them.
86 //! See the documentation for the [`log` crate][log-crate-url] for more
87 //! information about its API.
89 //! ## Enabling logging
91 //! Log levels are controlled on a per-module basis, and by default all logging
92 //! is disabled except for `error!`. Logging is controlled via the `RUST_LOG`
93 //! environment variable. The value of this environment variable is a
94 //! comma-separated list of logging directives. A logging directive is of the
98 //! path::to::module=level
101 //! The path to the module is rooted in the name of the crate it was compiled
102 //! for, so if your program is contained in a file `hello.rs`, for example, to
103 //! turn on logging for this file you would use a value of `RUST_LOG=hello`.
104 //! Furthermore, this path is a prefix-search, so all modules nested in the
105 //! specified module will also have logging enabled.
107 //! The actual `level` is optional to specify. If omitted, all logging will
108 //! be enabled. If specified, it must be one of the strings `debug`, `error`,
109 //! `info`, `warn`, or `trace`.
111 //! As the log level for a module is optional, the module to enable logging for
112 //! is also optional. If only a `level` is provided, then the global log
113 //! level for all modules is set to this value.
115 //! Some examples of valid values of `RUST_LOG` are:
117 //! * `hello` turns on all logging for the 'hello' module
118 //! * `info` turns on all info logging
119 //! * `hello=debug` turns on debug logging for 'hello'
120 //! * `hello,std::option` turns on hello, and std's option logging
121 //! * `error,hello=warn` turn on global error logging and also warn for hello
123 //! ## Filtering results
125 //! A `RUST_LOG` directive may include a regex filter. The syntax is to append `/`
126 //! followed by a regex. Each message is checked against the regex, and is only
127 //! logged if it matches. Note that the matching is done after formatting the
128 //! log string but before adding any logging meta-data. There is a single filter
133 //! * `hello/foo` turns on all logging for the 'hello' module where the log
134 //! message includes 'foo'.
135 //! * `info/f.o` turns on all info logging where the log message includes 'foo',
136 //! 'f1o', 'fao', etc.
137 //! * `hello=debug/foo*foo` turns on debug logging for 'hello' where the log
138 //! message includes 'foofoo' or 'fofoo' or 'fooooooofoo', etc.
139 //! * `error,hello=warn/[0-9]scopes` turn on global error logging and also
140 //! warn for hello. In both cases the log message must include a single digit
141 //! number followed by 'scopes'.
143 //! ## Capturing logs in tests
145 //! Records logged during `cargo test` will not be captured by the test harness by default.
146 //! The [`Builder::is_test`] method can be used in unit tests to ensure logs will be captured:
149 //! # #[macro_use] extern crate log;
150 //! # extern crate env_logger;
155 //! let _ = env_logger::builder().is_test(true).try_init();
162 //! info!("This record will be captured by `cargo test`");
164 //! assert_eq!(2, 1 + 1);
169 //! Enabling test capturing comes at the expense of color and other style support
170 //! and may have performance implications.
172 //! ## Disabling colors
174 //! Colors and other styles can be configured with the `RUST_LOG_STYLE`
175 //! environment variable. It accepts the following values:
177 //! * `auto` (default) will attempt to print style characters, but don't force the issue.
178 //! If the console isn't available on Windows, or if TERM=dumb, for example, then don't print colors.
179 //! * `always` will always print style characters even if they aren't supported by the terminal.
180 //! This includes emitting ANSI colors on Windows if the console API is unavailable.
181 //! * `never` will never print style characters.
183 //! ## Tweaking the default format
185 //! Parts of the default format can be excluded from the log output using the [`Builder`].
186 //! The following example excludes the timestamp from the log output:
189 //! env_logger::builder()
190 //! .default_format_timestamp(false)
194 //! ### Stability of the default format
196 //! The default format won't optimise for long-term stability, and explicitly makes no
197 //! guarantees about the stability of its output across major, minor or patch version
198 //! bumps during `0.x`.
200 //! If you want to capture or interpret the output of `env_logger` programmatically
201 //! then you should use a custom format.
203 //! ### Using a custom format
205 //! Custom formats can be provided as closures to the [`Builder`].
206 //! These closures take a [`Formatter`] and `log::Record` as arguments:
209 //! use std::io::Write;
211 //! env_logger::builder()
212 //! .format(|buf, record| {
213 //! writeln!(buf, "{}: {}", record.level(), record.args())
218 //! See the [`fmt`] module for more details about custom formats.
220 //! ## Specifying defaults for environment variables
222 //! `env_logger` can read configuration from environment variables.
223 //! If these variables aren't present, the default value to use can be tweaked with the [`Env`] type.
224 //! The following example defaults to log `warn` and above if the `RUST_LOG` environment variable
228 //! use env_logger::Env;
230 //! env_logger::from_env(Env::default().default_filter_or("warn")).init();
233 //! [log-crate-url]: https://docs.rs/log/
234 //! [`Builder`]: struct.Builder.html
235 //! [`Builder::is_test`]: struct.Builder.html#method.is_test
236 //! [`Env`]: struct.Env.html
237 //! [`fmt`]: fmt/index.html
239 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
240 html_favicon_url
= "https://www.rust-lang.org/static/images/favicon.ico",
241 html_root_url
= "https://docs.rs/env_logger/0.6.2")]
242 #![cfg_attr(test, deny(warnings))]
244 // When compiled for the rustc compiler itself we want to make sure that this is
246 #![cfg_attr(rustbuild, feature(staged_api, rustc_private))]
247 #![cfg_attr(rustbuild, unstable(feature = "rustc_private", issue = "27812"))]
249 #![deny(missing_debug_implementations, missing_docs, warnings)]
253 #[cfg(feature = "termcolor")]
254 extern crate termcolor
;
255 #[cfg(feature = "humantime")]
256 extern crate humantime
;
257 #[cfg(feature = "atty")]
261 use std
::borrow
::Cow
;
262 use std
::cell
::RefCell
;
264 use log
::{Log, LevelFilter, Record, SetLoggerError, Metadata}
;
269 pub use self::fmt
::glob
::*;
271 use self::filter
::Filter
;
272 use self::fmt
::Formatter
;
273 use self::fmt
::writer
::{self, Writer}
;
275 /// The default name for the environment variable to read filters from.
276 pub const DEFAULT_FILTER_ENV
: &'
static str = "RUST_LOG";
278 /// The default name for the environment variable to read style preferences from.
279 pub const DEFAULT_WRITE_STYLE_ENV
: &'
static str = "RUST_LOG_STYLE";
281 /// Set of environment variables to configure from.
283 /// # Default environment variables
285 /// By default, the `Env` will read the following environment variables:
287 /// - `RUST_LOG`: the level filter
288 /// - `RUST_LOG_STYLE`: whether or not to print styles with records.
290 /// These sources can be configured using the builder methods on `Env`.
294 write_style
: Var
<'a
>,
300 default: Option
<Cow
<'a
, str>>,
305 /// This struct implements the `Log` trait from the [`log` crate][log-crate-url],
306 /// which allows it to act as a logger.
308 /// The [`init()`], [`try_init()`], [`Builder::init()`] and [`Builder::try_init()`]
309 /// methods will each construct a `Logger` and immediately initialize it as the
310 /// default global logger.
312 /// If you'd instead need access to the constructed `Logger`, you can use
313 /// the associated [`Builder`] and install it with the
314 /// [`log` crate][log-crate-url] directly.
316 /// [log-crate-url]: https://docs.rs/log/
317 /// [`init()`]: fn.init.html
318 /// [`try_init()`]: fn.try_init.html
319 /// [`Builder::init()`]: struct.Builder.html#method.init
320 /// [`Builder::try_init()`]: struct.Builder.html#method.try_init
321 /// [`Builder`]: struct.Builder.html
325 #[allow(unknown_lints, bare_trait_objects)]
326 format
: Box
<Fn(&mut Formatter
, &Record
) -> io
::Result
<()> + Sync
+ Send
>,
329 /// `Builder` acts as builder for initializing a `Logger`.
331 /// It can be used to customize the log format, change the environment variable used
332 /// to provide the logging directives and also set the default log level filter.
338 /// extern crate log;
339 /// extern crate env_logger;
342 /// use std::io::Write;
343 /// use log::LevelFilter;
344 /// use env_logger::Builder;
347 /// let mut builder = Builder::from_default_env();
349 /// builder.format(|buf, record| writeln!(buf, "{} - {}", record.level(), record.args()))
350 /// .filter(None, LevelFilter::Info)
353 /// error!("error message");
354 /// info!("info message");
359 filter
: filter
::Builder
,
360 writer
: writer
::Builder
,
361 format
: fmt
::Builder
,
366 /// Initializes the log builder with defaults.
368 /// **NOTE:** This method won't read from any environment variables.
369 /// Use the [`filter`] and [`write_style`] methods to configure the builder
370 /// or use [`from_env`] or [`from_default_env`] instead.
374 /// Create a new builder and configure filters and style:
377 /// # extern crate log;
378 /// # extern crate env_logger;
380 /// use log::LevelFilter;
381 /// use env_logger::{Builder, WriteStyle};
383 /// let mut builder = Builder::new();
385 /// builder.filter(None, LevelFilter::Info)
386 /// .write_style(WriteStyle::Always)
391 /// [`filter`]: #method.filter
392 /// [`write_style`]: #method.write_style
393 /// [`from_env`]: #method.from_env
394 /// [`from_default_env`]: #method.from_default_env
395 pub fn new() -> Builder
{
399 /// Initializes the log builder from the environment.
401 /// The variables used to read configuration from can be tweaked before
406 /// Initialise a logger reading the log filter from an environment variable
410 /// use env_logger::Builder;
412 /// let mut builder = Builder::from_env("MY_LOG");
416 /// Initialise a logger using the `MY_LOG` variable for filtering and
417 /// `MY_LOG_STYLE` for whether or not to write styles:
420 /// use env_logger::{Builder, Env};
422 /// let env = Env::new().filter("MY_LOG").write_style("MY_LOG_STYLE");
424 /// let mut builder = Builder::from_env(env);
427 pub fn from_env
<'a
, E
>(env
: E
) -> Self
431 let mut builder
= Builder
::new();
432 let env
= env
.into();
434 if let Some(s
) = env
.get_filter() {
435 builder
.parse_filters(&s
);
438 if let Some(s
) = env
.get_write_style() {
439 builder
.parse_write_style(&s
);
445 /// Initializes the log builder from the environment using default variable names.
447 /// This method is a convenient way to call `from_env(Env::default())` without
448 /// having to use the `Env` type explicitly. The builder will use the
449 /// [default environment variables].
453 /// Initialise a logger using the default environment variables:
456 /// use env_logger::Builder;
458 /// let mut builder = Builder::from_default_env();
462 /// [default environment variables]: struct.Env.html#default-environment-variables
463 pub fn from_default_env() -> Self {
464 Self::from_env(Env
::default())
467 /// Sets the format function for formatting the log output.
469 /// This function is called on each record logged and should format the
470 /// log record and output it to the given [`Formatter`].
472 /// The format function is expected to output the string directly to the
473 /// `Formatter` so that implementations can use the [`std::fmt`] macros
474 /// to format and output without intermediate heap allocations. The default
475 /// `env_logger` formatter takes advantage of this.
479 /// Use a custom format to write only the log message:
482 /// use std::io::Write;
483 /// use env_logger::Builder;
485 /// let mut builder = Builder::new();
487 /// builder.format(|buf, record| writeln!(buf, "{}", record.args()));
490 /// [`Formatter`]: fmt/struct.Formatter.html
491 /// [`String`]: https://doc.rust-lang.org/stable/std/string/struct.String.html
492 /// [`std::fmt`]: https://doc.rust-lang.org/std/fmt/index.html
493 pub fn format
<F
: '
static>(&mut self, format
: F
) -> &mut Self
494 where F
: Fn(&mut Formatter
, &Record
) -> io
::Result
<()> + Sync
+ Send
496 self.format
.custom_format
= Some(Box
::new(format
));
500 /// Use the default format.
502 /// This method will clear any custom format set on the builder.
503 pub fn default_format(&mut self) -> &mut Self {
504 self.format
.custom_format
= None
;
508 /// Whether or not to write the level in the default format.
509 pub fn default_format_level(&mut self, write
: bool
) -> &mut Self {
510 self.format
.default_format_level
= write
;
514 /// Whether or not to write the module path in the default format.
515 pub fn default_format_module_path(&mut self, write
: bool
) -> &mut Self {
516 self.format
.default_format_module_path
= write
;
520 /// Whether or not to write the timestamp in the default format.
521 pub fn default_format_timestamp(&mut self, write
: bool
) -> &mut Self {
522 self.format
.default_format_timestamp
= write
;
526 /// Whether or not to write the timestamp with nanos.
527 pub fn default_format_timestamp_nanos(&mut self, write
: bool
) -> &mut Self {
528 self.format
.default_format_timestamp_nanos
= write
;
532 /// Adds a directive to the filter for a specific module.
536 /// Only include messages for warning and above for logs in `path::to::module`:
539 /// # extern crate log;
540 /// # extern crate env_logger;
542 /// use log::LevelFilter;
543 /// use env_logger::Builder;
545 /// let mut builder = Builder::new();
547 /// builder.filter_module("path::to::module", LevelFilter::Info);
550 pub fn filter_module(&mut self, module
: &str, level
: LevelFilter
) -> &mut Self {
551 self.filter
.filter_module(module
, level
);
555 /// Adds a directive to the filter for all modules.
559 /// Only include messages for warning and above for logs in `path::to::module`:
562 /// # extern crate log;
563 /// # extern crate env_logger;
565 /// use log::LevelFilter;
566 /// use env_logger::Builder;
568 /// let mut builder = Builder::new();
570 /// builder.filter_level(LevelFilter::Info);
573 pub fn filter_level(&mut self, level
: LevelFilter
) -> &mut Self {
574 self.filter
.filter_level(level
);
578 /// Adds filters to the logger.
580 /// The given module (if any) will log at most the specified level provided.
581 /// If no module is provided then the filter will apply to all log messages.
585 /// Only include messages for warning and above for logs in `path::to::module`:
588 /// # extern crate log;
589 /// # extern crate env_logger;
591 /// use log::LevelFilter;
592 /// use env_logger::Builder;
594 /// let mut builder = Builder::new();
596 /// builder.filter(Some("path::to::module"), LevelFilter::Info);
599 pub fn filter(&mut self,
600 module
: Option
<&str>,
601 level
: LevelFilter
) -> &mut Self {
602 self.filter
.filter(module
, level
);
606 /// Parses the directives string in the same form as the `RUST_LOG`
607 /// environment variable.
609 /// See the module documentation for more details.
610 #[deprecated(since = "0.6.1", note = "use `parse_filters` instead.")]
611 pub fn parse(&mut self, filters
: &str) -> &mut Self {
612 self.parse_filters(filters
)
615 /// Parses the directives string in the same form as the `RUST_LOG`
616 /// environment variable.
618 /// See the module documentation for more details.
619 pub fn parse_filters(&mut self, filters
: &str) -> &mut Self {
620 self.filter
.parse(filters
);
624 /// Sets the target for the log output.
626 /// Env logger can log to either stdout or stderr. The default is stderr.
630 /// Write log message to `stdout`:
633 /// use env_logger::{Builder, Target};
635 /// let mut builder = Builder::new();
637 /// builder.target(Target::Stdout);
639 pub fn target(&mut self, target
: fmt
::Target
) -> &mut Self {
640 self.writer
.target(target
);
644 /// Sets whether or not styles will be written.
646 /// This can be useful in environments that don't support control characters
647 /// for setting colors.
651 /// Never attempt to write styles:
654 /// use env_logger::{Builder, WriteStyle};
656 /// let mut builder = Builder::new();
658 /// builder.write_style(WriteStyle::Never);
660 pub fn write_style(&mut self, write_style
: fmt
::WriteStyle
) -> &mut Self {
661 self.writer
.write_style(write_style
);
665 /// Parses whether or not to write styles in the same form as the `RUST_LOG_STYLE`
666 /// environment variable.
668 /// See the module documentation for more details.
669 pub fn parse_write_style(&mut self, write_style
: &str) -> &mut Self {
670 self.writer
.parse_write_style(write_style
);
674 /// Sets whether or not the logger will be used in unit tests.
676 /// If `is_test` is `true` then the logger will allow the testing framework to
677 /// capture log records rather than printing them to the terminal directly.
678 pub fn is_test(&mut self, is_test
: bool
) -> &mut Self {
679 self.writer
.is_test(is_test
);
683 /// Initializes the global logger with the built env logger.
685 /// This should be called early in the execution of a Rust program. Any log
686 /// events that occur before initialization will be ignored.
690 /// This function will fail if it is called more than once, or if another
691 /// library has already initialized a global logger.
692 pub fn try_init(&mut self) -> Result
<(), SetLoggerError
> {
693 let logger
= self.build();
695 let max_level
= logger
.filter();
696 let r
= log
::set_boxed_logger(Box
::new(logger
));
699 log
::set_max_level(max_level
);
705 /// Initializes the global logger with the built env logger.
707 /// This should be called early in the execution of a Rust program. Any log
708 /// events that occur before initialization will be ignored.
712 /// This function will panic if it is called more than once, or if another
713 /// library has already initialized a global logger.
714 pub fn init(&mut self) {
715 self.try_init().expect("Builder::init should not be called after logger initialized");
718 /// Build an env logger.
720 /// The returned logger implements the `Log` trait and can be installed manually
721 /// or nested within another logger.
722 pub fn build(&mut self) -> Logger
{
723 assert
!(!self.built
, "attempt to re-use consumed builder");
727 writer
: self.writer
.build(),
728 filter
: self.filter
.build(),
729 format
: self.format
.build(),
735 /// Creates the logger from the environment.
737 /// The variables used to read configuration from can be tweaked before
742 /// Create a logger reading the log filter from an environment variable
746 /// use env_logger::Logger;
748 /// let logger = Logger::from_env("MY_LOG");
751 /// Create a logger using the `MY_LOG` variable for filtering and
752 /// `MY_LOG_STYLE` for whether or not to write styles:
755 /// use env_logger::{Logger, Env};
757 /// let env = Env::new().filter_or("MY_LOG", "info").write_style_or("MY_LOG_STYLE", "always");
759 /// let logger = Logger::from_env(env);
761 pub fn from_env
<'a
, E
>(env
: E
) -> Self
765 Builder
::from_env(env
).build()
768 /// Creates the logger from the environment using default variable names.
770 /// This method is a convenient way to call `from_env(Env::default())` without
771 /// having to use the `Env` type explicitly. The logger will use the
772 /// [default environment variables].
776 /// Creates a logger using the default environment variables:
779 /// use env_logger::Logger;
781 /// let logger = Logger::from_default_env();
784 /// [default environment variables]: struct.Env.html#default-environment-variables
785 pub fn from_default_env() -> Self {
786 Builder
::from_default_env().build()
789 /// Returns the maximum `LevelFilter` that this env logger instance is
790 /// configured to output.
791 pub fn filter(&self) -> LevelFilter
{
795 /// Checks if this record matches the configured filter.
796 pub fn matches(&self, record
: &Record
) -> bool
{
797 self.filter
.matches(record
)
801 impl Log
for Logger
{
802 fn enabled(&self, metadata
: &Metadata
) -> bool
{
803 self.filter
.enabled(metadata
)
806 fn log(&self, record
: &Record
) {
807 if self.matches(record
) {
808 // Log records are written to a thread-local buffer before being printed
809 // to the terminal. We clear these buffers afterwards, but they aren't shrinked
810 // so will always at least have capacity for the largest log record formatted
813 // If multiple `Logger`s are used by the same threads then the thread-local
814 // formatter might have different color support. If this is the case the
815 // formatter and its buffer are discarded and recreated.
818 static FORMATTER
: RefCell
<Option
<Formatter
>> = RefCell
::new(None
);
821 FORMATTER
.with(|tl_buf
| {
822 // It's possible for implementations to sometimes
823 // log-while-logging (e.g. a `std::fmt` implementation logs
824 // internally) but it's super rare. If this happens make sure we
825 // at least don't panic and ship some output to the screen.
828 let tl_buf
= match tl_buf
.try_borrow_mut() {
836 // Check the buffer style. If it's different from the logger's
837 // style then drop the buffer and recreate it.
839 Some(ref mut formatter
) => {
840 if formatter
.write_style() != self.writer
.write_style() {
841 *formatter
= Formatter
::new(&self.writer
)
844 ref mut tl_buf
=> *tl_buf
= Some(Formatter
::new(&self.writer
))
847 // The format is guaranteed to be `Some` by this point
848 let mut formatter
= tl_buf
.as_mut().unwrap();
850 let _
= (self.format
)(&mut formatter
, record
).and_then(|_
| formatter
.print(&self.writer
));
852 // Always clear the buffer afterwards
862 /// Get a default set of environment variables.
863 pub fn new() -> Self {
867 /// Specify an environment variable to read the filter from.
868 pub fn filter
<E
>(mut self, filter_env
: E
) -> Self
870 E
: Into
<Cow
<'a
, str>>
872 self.filter
= Var
::new(filter_env
);
877 /// Specify an environment variable to read the filter from.
879 /// If the variable is not set, the default value will be used.
880 pub fn filter_or
<E
, V
>(mut self, filter_env
: E
, default: V
) -> Self
882 E
: Into
<Cow
<'a
, str>>,
883 V
: Into
<Cow
<'a
, str>>,
885 self.filter
= Var
::new_with_default(filter_env
, default);
890 /// Use the default environment variable to read the filter from.
892 /// If the variable is not set, the default value will be used.
893 pub fn default_filter_or
<V
>(mut self, default: V
) -> Self
895 V
: Into
<Cow
<'a
, str>>,
897 self.filter
= Var
::new_with_default(DEFAULT_FILTER_ENV
, default);
902 fn get_filter(&self) -> Option
<String
> {
906 /// Specify an environment variable to read the style from.
907 pub fn write_style
<E
>(mut self, write_style_env
: E
) -> Self
909 E
: Into
<Cow
<'a
, str>>
911 self.write_style
= Var
::new(write_style_env
);
916 /// Specify an environment variable to read the style from.
918 /// If the variable is not set, the default value will be used.
919 pub fn write_style_or
<E
, V
>(mut self, write_style_env
: E
, default: V
) -> Self
921 E
: Into
<Cow
<'a
, str>>,
922 V
: Into
<Cow
<'a
, str>>,
924 self.write_style
= Var
::new_with_default(write_style_env
, default);
929 /// Use the default environment variable to read the style from.
931 /// If the variable is not set, the default value will be used.
932 pub fn default_write_style_or
<V
>(mut self, default: V
) -> Self
934 V
: Into
<Cow
<'a
, str>>,
936 self.write_style
= Var
::new_with_default(DEFAULT_WRITE_STYLE_ENV
, default);
941 fn get_write_style(&self) -> Option
<String
> {
942 self.write_style
.get()
947 fn new
<E
>(name
: E
) -> Self
949 E
: Into
<Cow
<'a
, str>>,
957 fn new_with_default
<E
, V
>(name
: E
, default: V
) -> Self
959 E
: Into
<Cow
<'a
, str>>,
960 V
: Into
<Cow
<'a
, str>>,
964 default: Some(default.into()),
968 fn get(&self) -> Option
<String
> {
969 env
::var(&*self.name
)
971 .or_else(|| self.default
973 .map(|v
| v
.into_owned()))
977 impl<'a
, T
> From
<T
> for Env
<'a
>
979 T
: Into
<Cow
<'a
, str>>
981 fn from(filter_env
: T
) -> Self {
982 Env
::default().filter(filter_env
.into())
986 impl<'a
> Default
for Env
<'a
> {
987 fn default() -> Self {
989 filter
: Var
::new(DEFAULT_FILTER_ENV
),
990 write_style
: Var
::new(DEFAULT_WRITE_STYLE_ENV
),
999 impl fmt
::Debug
for Logger
{
1000 fn fmt(&self, f
: &mut fmt
::Formatter
)->fmt
::Result
{
1001 f
.debug_struct("Logger")
1002 .field("filter", &self.filter
)
1007 impl fmt
::Debug
for Builder
{
1008 fn fmt(&self, f
: &mut fmt
::Formatter
)->fmt
::Result
{
1010 f
.debug_struct("Logger")
1011 .field("built", &true)
1014 f
.debug_struct("Logger")
1015 .field("filter", &self.filter
)
1016 .field("writer", &self.writer
)
1023 /// Attempts to initialize the global logger with an env logger.
1025 /// This should be called early in the execution of a Rust program. Any log
1026 /// events that occur before initialization will be ignored.
1030 /// This function will fail if it is called more than once, or if another
1031 /// library has already initialized a global logger.
1032 pub fn try_init() -> Result
<(), SetLoggerError
> {
1033 try_init_from_env(Env
::default())
1036 /// Initializes the global logger with an env logger.
1038 /// This should be called early in the execution of a Rust program. Any log
1039 /// events that occur before initialization will be ignored.
1043 /// This function will panic if it is called more than once, or if another
1044 /// library has already initialized a global logger.
1046 try_init().expect("env_logger::init should not be called after logger initialized");
1049 /// Attempts to initialize the global logger with an env logger from the given
1050 /// environment variables.
1052 /// This should be called early in the execution of a Rust program. Any log
1053 /// events that occur before initialization will be ignored.
1057 /// Initialise a logger using the `MY_LOG` environment variable for filters
1058 /// and `MY_LOG_STYLE` for writing colors:
1061 /// # extern crate env_logger;
1062 /// use env_logger::{Builder, Env};
1064 /// # fn run() -> Result<(), Box<::std::error::Error>> {
1065 /// let env = Env::new().filter("MY_LOG").write_style("MY_LOG_STYLE");
1067 /// env_logger::try_init_from_env(env)?;
1071 /// # fn main() { run().unwrap(); }
1076 /// This function will fail if it is called more than once, or if another
1077 /// library has already initialized a global logger.
1078 pub fn try_init_from_env
<'a
, E
>(env
: E
) -> Result
<(), SetLoggerError
>
1082 let mut builder
= Builder
::from_env(env
);
1087 /// Initializes the global logger with an env logger from the given environment
1090 /// This should be called early in the execution of a Rust program. Any log
1091 /// events that occur before initialization will be ignored.
1095 /// Initialise a logger using the `MY_LOG` environment variable for filters
1096 /// and `MY_LOG_STYLE` for writing colors:
1099 /// use env_logger::{Builder, Env};
1101 /// let env = Env::new().filter("MY_LOG").write_style("MY_LOG_STYLE");
1103 /// env_logger::init_from_env(env);
1108 /// This function will panic if it is called more than once, or if another
1109 /// library has already initialized a global logger.
1110 pub fn init_from_env
<'a
, E
>(env
: E
)
1114 try_init_from_env(env
).expect("env_logger::init_from_env should not be called after logger initialized");
1117 /// Create a new builder with the default environment variables.
1119 /// The builder can be configured before being initialized.
1120 pub fn builder() -> Builder
{
1121 Builder
::from_default_env()
1124 /// Create a builder from the given environment variables.
1126 /// The builder can be configured before being initialized.
1127 pub fn from_env
<'a
, E
>(env
: E
) -> Builder
1131 Builder
::from_env(env
)
1139 fn env_get_filter_reads_from_var_if_set() {
1140 env
::set_var("env_get_filter_reads_from_var_if_set", "from var");
1142 let env
= Env
::new().filter_or("env_get_filter_reads_from_var_if_set", "from default");
1144 assert_eq
!(Some("from var".to_owned()), env
.get_filter());
1148 fn env_get_filter_reads_from_default_if_var_not_set() {
1149 env
::remove_var("env_get_filter_reads_from_default_if_var_not_set");
1151 let env
= Env
::new().filter_or("env_get_filter_reads_from_default_if_var_not_set", "from default");
1153 assert_eq
!(Some("from default".to_owned()), env
.get_filter());
1157 fn env_get_write_style_reads_from_var_if_set() {
1158 env
::set_var("env_get_write_style_reads_from_var_if_set", "from var");
1160 let env
= Env
::new().write_style_or("env_get_write_style_reads_from_var_if_set", "from default");
1162 assert_eq
!(Some("from var".to_owned()), env
.get_write_style());
1166 fn env_get_write_style_reads_from_default_if_var_not_set() {
1167 env
::remove_var("env_get_write_style_reads_from_default_if_var_not_set");
1169 let env
= Env
::new().write_style_or("env_get_write_style_reads_from_default_if_var_not_set", "from default");
1171 assert_eq
!(Some("from default".to_owned()), env
.get_write_style());