diff options
Diffstat (limited to 'third_party/rust/env_logger/examples')
8 files changed, 331 insertions, 0 deletions
diff --git a/third_party/rust/env_logger/examples/custom_default_format.rs b/third_party/rust/env_logger/examples/custom_default_format.rs new file mode 100644 index 0000000000..b04eb6028d --- /dev/null +++ b/third_party/rust/env_logger/examples/custom_default_format.rs @@ -0,0 +1,40 @@ +/*! +Disabling parts of the default format. + +Before running this example, try setting the `MY_LOG_LEVEL` environment variable to `info`: + +```no_run,shell +$ export MY_LOG_LEVEL='info' +``` + +Also try setting the `MY_LOG_STYLE` environment variable to `never` to disable colors +or `auto` to enable them: + +```no_run,shell +$ export MY_LOG_STYLE=never +``` + +If you want to control the logging output completely, see the `custom_logger` example. +*/ + +#[macro_use] +extern crate log; + +use env_logger::{Builder, Env}; + +fn init_logger() { + let env = Env::default() + .filter("MY_LOG_LEVEL") + .write_style("MY_LOG_STYLE"); + + Builder::from_env(env) + .format_level(false) + .format_timestamp_nanos() + .init(); +} + +fn main() { + init_logger(); + + info!("a log from `MyLogger`"); +} diff --git a/third_party/rust/env_logger/examples/custom_format.rs b/third_party/rust/env_logger/examples/custom_format.rs new file mode 100644 index 0000000000..cc16b336ff --- /dev/null +++ b/third_party/rust/env_logger/examples/custom_format.rs @@ -0,0 +1,54 @@ +/*! +Changing the default logging format. + +Before running this example, try setting the `MY_LOG_LEVEL` environment variable to `info`: + +```no_run,shell +$ export MY_LOG_LEVEL='info' +``` + +Also try setting the `MY_LOG_STYLE` environment variable to `never` to disable colors +or `auto` to enable them: + +```no_run,shell +$ export MY_LOG_STYLE=never +``` + +If you want to control the logging output completely, see the `custom_logger` example. +*/ + +#[cfg(all(feature = "color", feature = "humantime"))] +fn main() { + use env_logger::{fmt::Color, Builder, Env}; + + use std::io::Write; + + fn init_logger() { + let env = Env::default() + .filter("MY_LOG_LEVEL") + .write_style("MY_LOG_STYLE"); + + Builder::from_env(env) + .format(|buf, record| { + let mut style = buf.style(); + style.set_bg(Color::Yellow).set_bold(true); + + let timestamp = buf.timestamp(); + + writeln!( + buf, + "My formatted log ({}): {}", + timestamp, + style.value(record.args()) + ) + }) + .init(); + } + + init_logger(); + + log::info!("a log from `MyLogger`"); +} + +#[cfg(not(all(feature = "color", feature = "humantime")))] +fn main() {} diff --git a/third_party/rust/env_logger/examples/custom_logger.rs b/third_party/rust/env_logger/examples/custom_logger.rs new file mode 100644 index 0000000000..ca3a4a9012 --- /dev/null +++ b/third_party/rust/env_logger/examples/custom_logger.rs @@ -0,0 +1,62 @@ +/*! +Using `env_logger` to drive a custom logger. + +Before running this example, try setting the `MY_LOG_LEVEL` environment variable to `info`: + +```no_run,shell +$ export MY_LOG_LEVEL='info' +``` + +If you only want to change the way logs are formatted, look at the `custom_format` example. +*/ + +#[macro_use] +extern crate log; + +use env_logger::filter::{Builder, Filter}; + +use log::{Log, Metadata, Record, SetLoggerError}; + +const FILTER_ENV: &str = "MY_LOG_LEVEL"; + +struct MyLogger { + inner: Filter, +} + +impl MyLogger { + fn new() -> MyLogger { + let mut builder = Builder::from_env(FILTER_ENV); + + MyLogger { + inner: builder.build(), + } + } + + fn init() -> Result<(), SetLoggerError> { + let logger = Self::new(); + + log::set_max_level(logger.inner.filter()); + log::set_boxed_logger(Box::new(logger)) + } +} + +impl Log for MyLogger { + fn enabled(&self, metadata: &Metadata) -> bool { + self.inner.enabled(metadata) + } + + fn log(&self, record: &Record) { + // Check if the record is matched by the logger before logging + if self.inner.matches(record) { + println!("{} - {}", record.level(), record.args()); + } + } + + fn flush(&self) {} +} + +fn main() { + MyLogger::init().unwrap(); + + info!("a log from `MyLogger`"); +} diff --git a/third_party/rust/env_logger/examples/default.rs b/third_party/rust/env_logger/examples/default.rs new file mode 100644 index 0000000000..67bb030745 --- /dev/null +++ b/third_party/rust/env_logger/examples/default.rs @@ -0,0 +1,38 @@ +/*! +Using `env_logger`. + +Before running this example, try setting the `MY_LOG_LEVEL` environment variable to `info`: + +```no_run,shell +$ export MY_LOG_LEVEL='info' +``` + +Also try setting the `MY_LOG_STYLE` environment variable to `never` to disable colors +or `auto` to enable them: + +```no_run,shell +$ export MY_LOG_STYLE=never +``` +*/ + +#[macro_use] +extern crate log; + +use env_logger::Env; + +fn main() { + // The `Env` lets us tweak what the environment + // variables to read are and what the default + // value is if they're missing + let env = Env::default() + .filter_or("MY_LOG_LEVEL", "trace") + .write_style_or("MY_LOG_STYLE", "always"); + + env_logger::init_from_env(env); + + trace!("some trace log"); + debug!("some debug log"); + info!("some information log"); + warn!("some warning log"); + error!("some error log"); +} diff --git a/third_party/rust/env_logger/examples/direct_logger.rs b/third_party/rust/env_logger/examples/direct_logger.rs new file mode 100644 index 0000000000..4d7f39d0ae --- /dev/null +++ b/third_party/rust/env_logger/examples/direct_logger.rs @@ -0,0 +1,39 @@ +/*! +Using `env_logger::Logger` and the `log::Log` trait directly. + +This example doesn't rely on environment variables, or having a static logger installed. +*/ + +use env_logger::{Builder, WriteStyle}; + +use log::{Level, LevelFilter, Log, MetadataBuilder, Record}; + +fn record() -> Record<'static> { + let error_metadata = MetadataBuilder::new() + .target("myApp") + .level(Level::Error) + .build(); + + Record::builder() + .metadata(error_metadata) + .args(format_args!("Error!")) + .line(Some(433)) + .file(Some("app.rs")) + .module_path(Some("server")) + .build() +} + +fn main() { + let stylish_logger = Builder::new() + .filter(None, LevelFilter::Error) + .write_style(WriteStyle::Always) + .build(); + + let unstylish_logger = Builder::new() + .filter(None, LevelFilter::Error) + .write_style(WriteStyle::Never) + .build(); + + stylish_logger.log(&record()); + unstylish_logger.log(&record()); +} diff --git a/third_party/rust/env_logger/examples/filters_from_code.rs b/third_party/rust/env_logger/examples/filters_from_code.rs new file mode 100644 index 0000000000..c877a44253 --- /dev/null +++ b/third_party/rust/env_logger/examples/filters_from_code.rs @@ -0,0 +1,20 @@ +/*! +Specify logging filters in code instead of using an environment variable. +*/ + +#[macro_use] +extern crate log; + +use env_logger::Builder; + +use log::LevelFilter; + +fn main() { + Builder::new().filter_level(LevelFilter::max()).init(); + + trace!("some trace log"); + debug!("some debug log"); + info!("some information log"); + warn!("some warning log"); + error!("some error log"); +} diff --git a/third_party/rust/env_logger/examples/in_tests.rs b/third_party/rust/env_logger/examples/in_tests.rs new file mode 100644 index 0000000000..c4487cc9c1 --- /dev/null +++ b/third_party/rust/env_logger/examples/in_tests.rs @@ -0,0 +1,54 @@ +/*! +Using `env_logger` in tests. + +Log events will be captured by `cargo` and only printed if the test fails. +You can run this example by calling: + +```text +cargo test --example in_tests +``` + +You should see the `it_does_not_work` test fail and include its log output. +*/ + +#[cfg_attr(test, macro_use)] +extern crate log; + +fn main() {} + +#[cfg(test)] +mod tests { + fn init_logger() { + let _ = env_logger::builder() + // Include all events in tests + .filter_level(log::LevelFilter::max()) + // Ensure events are captured by `cargo test` + .is_test(true) + // Ignore errors initializing the logger if tests race to configure it + .try_init(); + } + + #[test] + fn it_works() { + init_logger(); + + let a = 1; + let b = 2; + + debug!("checking whether {} + {} = 3", a, b); + + assert_eq!(3, a + b); + } + + #[test] + fn it_does_not_work() { + init_logger(); + + let a = 1; + let b = 2; + + debug!("checking whether {} + {} = 6", a, b); + + assert_eq!(6, a + b); + } +} diff --git a/third_party/rust/env_logger/examples/syslog_friendly_format.rs b/third_party/rust/env_logger/examples/syslog_friendly_format.rs new file mode 100644 index 0000000000..9809ab3f87 --- /dev/null +++ b/third_party/rust/env_logger/examples/syslog_friendly_format.rs @@ -0,0 +1,24 @@ +use std::io::Write;
+
+fn main() {
+ match std::env::var("RUST_LOG_STYLE") {
+ Ok(s) if s == "SYSTEMD" => env_logger::builder()
+ .format(|buf, record| {
+ writeln!(
+ buf,
+ "<{}>{}: {}",
+ match record.level() {
+ log::Level::Error => 3,
+ log::Level::Warn => 4,
+ log::Level::Info => 6,
+ log::Level::Debug => 7,
+ log::Level::Trace => 7,
+ },
+ record.target(),
+ record.args()
+ )
+ })
+ .init(),
+ _ => env_logger::init(),
+ };
+}
|