Complete exercise: logging

This commit is contained in:
2026-05-26 00:08:56 +04:00
parent d745026c1a
commit 621fb6bb59
3 changed files with 14 additions and 9 deletions

View File

@@ -4,10 +4,5 @@ version = "0.1.0"
edition = "2021"
[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.9"
log = "0.4" # I'm glad you came to add the `log` dependency! I got it all ready for you, just uncomment:
env_logger = "0.9" # And here's the env_logger dependency that you'll need in main.rs

View File

@@ -6,6 +6,8 @@
//
// Hint: You need to update Cargo.toml to add the `log` dependency, first.
use log::{error, warn, info, debug, trace};
#[derive(Debug)]
pub struct Frog {
energy: u8,
@@ -15,19 +17,23 @@ pub struct Frog {
impl Frog {
pub fn new() -> Self {
// 2. Use debug!() to log "A new Frog has been created"
debug!(target: "Frog::new", "A new Frog has been created");
Default::default()
}
pub fn hop(&mut self) {
self.energy -= 1;
// 3. Use info!() to log that a Frog hopped, and how much energy is left
info!(target: "Frog::hop", "A frog hopped! It has {} energy left", self.energy);
if self.energy == 0 {
// 4. Use warn!() to warn that the frog will go to sleep since he ran out of energy
warn!(target: "Frog::hop", "The frog will go to sleep since he ran out of energy");
self.sleep();
}
}
pub fn sleep(&mut self) {
if self.sleeping {
// 5. Use error!() to log a (non-fatal) error stating that the Frog is already asleep
error!(target: "Frog::sleep", "The frog is already asleep");
} else {
self.sleeping = true;
}
@@ -37,9 +43,12 @@ impl Frog {
impl Default for Frog {
fn default() -> Self {
// 6. Use trace!() to log that a default value was generated, with the debug representation
Frog {
let frog = Frog {
energy: 5,
sleeping: false,
}
};
trace!(target: "Frog::Default", "A default Frog value was generated: {:?}", frog);
frog
}
}

View File

@@ -8,6 +8,7 @@ use frogger::Frog;
fn main() {
// 8. Initialize env_logger using the init() function at the top level of the library
env_logger::init();
// 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`