Add logging exercise

This commit is contained in:
Nathan Stocks
2021-06-16 14:00:46 -06:00
parent 3f40b561e9
commit 62cca13e9b
4 changed files with 82 additions and 0 deletions

View File

@@ -12,4 +12,5 @@ members = [
"exercise/errors",
"exercise/testing",
"exercise/threads_channels",
"exercise/logging",
]

View File

@@ -0,0 +1,12 @@
[package]
name = "frogger"
version = "0.1.0"
authors = ["Nathan Stocks <nathan@agileperception.com>"]
edition = "2018"
[dependencies]
# I'm glad you came to add the `log` dependency! I got it all ready for you, just uncomment:
log = "0.4"
# And here's the env_logger dependency that you'll need in main.rs
env_logger = "0.8"

View 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,
}
}
}

View 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`
}