How to do it...

Follow these steps:

  1. Open the Cargo.toml file that has been generated earlier for you.

  2. Under [dependencies], add the following line:

log = "0.4.1"
env_logger = "0.5.3"
  1. If you want, you can go to log's (https://crates.io/crates/log) or env_logger's (https://crates.io/crates/env_log) crates.io pages to check for the newest version and use that one instead.
  2. In the folder bin, create a file called logging.rs.
  3. Add the following code and run it with RUST_LOG=logging cargo run --bin logging if you're on a Unix-based system. Otherwise, run $env:RUST_LOG="logging"; cargo run --bin logging on Windows:

1   extern crate env_logger;
2 #[macro_use]
3 extern crate log;
4 use log::Level;
5
6 fn main() {
7 // env_logger's priority levels are:
8 // error > warn > info > debug > trace
9 env_logger::init();
10 // All logging calls log! in the background
11 log!(Level::Debug, "env_logger has been initialized");
12
13 // There are convenience macros for every logging level
however
14 info!("The program has started!");
15
16 // A log's target is its parent module per default
17 // ('logging' in our case, as we're in a binary)
18 // We can override this target however:
19 info!(target: "extra_info", "This is additional info that
will only show if you
20 activate info level logging for the extra_info target");
21
22 warn!("Something that requires your attention happened");
23
24 // Only execute code if logging level is active
25 if log_enabled!(Level::Debug) {
26 let data = expensive_operation();
27 debug!("The expensive operation returned: "{}"", data);
28 }
29
30 error!("Something terrible happened!");
31 }
32
33 fn expensive_operation() -> String {
34 trace!("Starting an expensive operation");
35 let data = "Imagine this is a very very expensive
task".to_string();
36 trace!("Finished the expensive operation");
37 data
38 }
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.68.18