CodeTheRobot

C++ Advanced · Lesson 06 of 23

Logging patterns

Log levels, structured messages, throttling and keeping logging out of hot loops.

Estimated time · 45–75 min

Learning goals

What you will understand

  • Explain logging patterns in your own words
  • Use it in a small robotics example
  • Verify the result instead of assuming it worked

Understand the idea first

The mental model

Logging is how a running robot explains itself. Use levels (debug, info, warn, error, fatal), include the component name and the values that matter, and make messages searchable. ROS 2 provides RCLCPP_INFO, RCLCPP_WARN and RCLCPP_ERROR with the same idea.

Logging costs time. Do not print inside a fast control loop; throttle repeated messages (once per second) and keep a level filter so debug output can be turned off. Never log secrets, and always log the reason with the error.

Guided lesson

Work through these steps

  1. 1.

    Read the logging patterns example and identify what each line owns or changes.

  2. 2.

    Create a small source file, compile with -std=c++17 and warnings enabled, and run it.

  3. 3.

    Change one input, predict the result before running, then compare the output.

  4. 4.

    Record one compiler or runtime error and explain the correction in your own words.

Worked example

Read it before you run it

enum class Level { debug, info, warn, error };
// Ordered severity levels.
class Logger {
// A tiny logger with a level filter.
public:
// Public interface.
  explicit Logger(std::string name, Level min = Level::info) : name_{std::move(name)}, min_{min} {}
// Store the component name and the lowest level to print.
  void log(Level lvl, const std::string& msg) const {
// Print a message if it is important enough.
    if (lvl < min_) return;
// Filtered out: cheap and silent.
    std::cerr << '[' << name_ << "] " << msg << '\n';
// Write to stderr with the component name.
  }
// End of log.
private:
// Hidden state.
  std::string name_; Level min_;
// Component name and threshold.
};
// End of the class.
Logger log{"arm_driver"};
// Create a logger for one component.
log.log(Level::warn, "joint 3 near limit: 1.48 rad");
// A useful message: what, where and the value.

What the example is doing

  1. 1.Read declarations from right to left: identify each value's type, name, and initial value.
  2. 2.Follow the data through each expression before considering syntax shortcuts.
  3. 3.Compile with warnings enabled; a clean build is part of the result, not an optional polish step.

Watch it run · The robot's computer

See what this code does

The terminal types this lesson's practice solution and runs it. The scene shows the kind of robot behaviour that code drives. It plays by itself and loops.

robot computercpumemdiskdriverstoppedplannerstoppedloggerstoppedsafetystoppedTHE ROBOT'S COMPUTER

Demo for Logging patterns. Expected result: [arm] joint 3 near limit

Practice code

Now type it yourself

Copy the starter into practice.cpp and replace every TODO with your own code. Build and run it: g++ -std=c++17 -Wall -Wextra -Wpedantic practice.cpp -o practice -pthread && ./practice

#include <iostream>
#include <string>

enum class Level { debug, info, warn, error };

class Logger {
 public:
  explicit Logger(std::string name, Level min = Level::info) : name_{std::move(name)}, min_{min} {}
  void log(Level lvl, const std::string& msg) const {
    // TODO: return silently when lvl is below min_; otherwise print "[name] msg"
  }

 private:
  std::string name_;
  Level min_;
};

int main() {
  Logger log{"arm"};
  log.log(Level::debug, "raw encoder value 8123");  // hidden: below the info threshold
  log.log(Level::warn, "joint 3 near limit");
  return 0;
}

Expected output

[arm] joint 3 near limit
Stuck? Show the full solution (try it yourself first)
#include <iostream>
#include <string>

enum class Level { debug, info, warn, error };

class Logger {
 public:
  explicit Logger(std::string name, Level min = Level::info) : name_{std::move(name)}, min_{min} {}
  void log(Level lvl, const std::string& msg) const {
    if (lvl < min_) return;
    std::cout << '[' << name_ << "] " << msg << '\n';
  }

 private:
  std::string name_;
  Level min_;
};

int main() {
  Logger log{"arm"};
  log.log(Level::debug, "raw encoder value 8123");  // hidden: below the info threshold
  log.log(Level::warn, "joint 3 near limit");
  return 0;
}

Expected result

How you know it worked

  • After adding the shown fragment to the guided exercise with its listed headers and surrounding program, the finished program builds with -Wall -Wextra -Wpedantic.
  • Changing the stated input produces the result you predicted.

Practical exercise

Apply the lesson

Add a throttled warn() to the logger that prints at most once per second using steady_clock. Call it 1,000 times in a loop and confirm it printed only a few lines.

Before you continue

  • The program builds with -std=c++17 and no warnings
  • You can explain the key rule without reading the example
  • The normal and edge cases both have recorded results

If something goes wrong

The compiler reports that a name or type is unknown.

Start at the first error. Check spelling, required #include lines, and whether the declaration appears before use.

The program runs but the value is wrong.

Print the inputs and intermediate values, then check conversions, units, and collection order.