Add logging exercise
This commit is contained in:
44
exercise/logging/src/lib.rs
Normal file
44
exercise/logging/src/lib.rs
Normal file
@@ -0,0 +1,44 @@
|
||||
// 1. Bring the macros error, warn, info, debug, and trace into scope from the log package with a
|
||||
// `use` statement.
|
||||
//
|
||||
// - You should be able to run `cargo build --lib` successfully after each step.
|
||||
//
|
||||
// Hint: You may need to update Cargo.toml first
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Frog {
|
||||
energy: u8,
|
||||
sleeping: bool,
|
||||
}
|
||||
|
||||
impl Frog {
|
||||
pub fn new() -> Self {
|
||||
// 2. Use debug!() to log "A new Frog has been created"
|
||||
Default::default()
|
||||
}
|
||||
pub fn hop(&mut self) {
|
||||
// 3. Use info!() to log that a Frog hopped, and how much energy is left
|
||||
self.energy -= 1;
|
||||
if self.energy == 0 {
|
||||
// 4. Use warn!() to warn that the frog will go to sleep since he ran out of energy
|
||||
self.sleep();
|
||||
}
|
||||
}
|
||||
// info, error
|
||||
pub fn sleep(&mut self) {
|
||||
if !self.sleeping {
|
||||
// 5. Use error!() to log a (non-fatal) error stating that the Frog is already asleep
|
||||
self.sleeping = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Frog {
|
||||
fn default() -> Self {
|
||||
// 6. Use trace!() to log that a default value was generated, with the debug representation
|
||||
Frog {
|
||||
energy: 5,
|
||||
sleeping: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
25
exercise/logging/src/main.rs
Normal file
25
exercise/logging/src/main.rs
Normal file
@@ -0,0 +1,25 @@
|
||||
// START IN lib.rs!!!
|
||||
|
||||
use frogger::Frog;
|
||||
|
||||
// You did 1-6 in lib.rs already, right?
|
||||
//
|
||||
// 7. Bring env_logger into scope. You might need to update Cargo.toml, first.
|
||||
|
||||
fn main() {
|
||||
// 8. Initialize env_logger using the init() function
|
||||
|
||||
// 9. Run this program with `cargo run` and take a look at the default output.
|
||||
// - Now run it again with an explicit log level, like `RUST_LOG=info cargo run`
|
||||
// - ...and `RUST_LOG=trace cargo run`
|
||||
let mut skippy = Frog::new();
|
||||
skippy.hop();
|
||||
skippy.hop();
|
||||
skippy.hop();
|
||||
skippy.hop();
|
||||
skippy.hop();
|
||||
skippy.sleep();
|
||||
|
||||
// Challenge: Go back to lib.rs and set the `target: ` argument for each logging call to be the
|
||||
// path to the function. For example, `Frog::new`
|
||||
}
|
||||
Reference in New Issue
Block a user