feat(logger): Enhance logging functionality with variadic templates for formatted messages

- Added variadic template methods to the Logger class for formatted logging at different log levels (debug, info, warn, error).
- Updated existing logging calls in CustomRobot to utilize the new formatted logging methods for improved readability and consistency.
- Removed the old log method implementation from logger.cpp to streamline the codebase.
This commit is contained in:
2025-09-22 19:35:03 +08:00
parent 5247295521
commit 20d75ca377
3 changed files with 64 additions and 62 deletions

View File

@@ -321,13 +321,13 @@ bool CustomRobot::processLowCmd(const std::string& cmd, const nlohmann::json& me
}
else
{
LOG_ERROR("Unknown Low command: " + cmd);
LOG_ERROR("Unknown Low command: %s", cmd.c_str());
return false;
}
}
catch (const std::exception& e)
{
LOG_ERROR("Error executing Low command " + cmd + ": " + std::string(e.what()));
LOG_ERROR("Error executing Low command %s: %s", cmd.c_str(), e.what());
return false;
}
}

View File

@@ -46,42 +46,6 @@ void Logger::log(LogLevel level, const std::string& message) {
}
}
template<typename... Args>
void Logger::log(LogLevel level, const char* format, Args... args)
{
if (level < currentLevel_) {
return;
}
// A buffer to hold the formatted string.
// First, we try with a small buffer.
char buffer[256];
int size = snprintf(buffer, sizeof(buffer), format, args...);
if (size < 0) {
// Encoding error
error("Encoding error in log message.");
return;
}
std::string message;
if (size < sizeof(buffer)) {
// The message fit in the buffer.
message = buffer;
} else {
// The buffer was too small, we need to allocate a larger one.
std::unique_ptr<char[]> dynamic_buffer(new char[size + 1]);
int new_size = snprintf(dynamic_buffer.get(), size + 1, format, args...);
if (new_size >= 0 && new_size <= size) {
message = dynamic_buffer.get();
} else {
error("Encoding error in log message after buffer resize.");
return;
}
}
log(level, message);
}
void Logger::debug(const std::string& message) {
log(LogLevel::DEBUG, message);
}
@@ -98,30 +62,6 @@ void Logger::error(const std::string& message) {
log(LogLevel::ERROR, message);
}
template<typename... Args>
void Logger::debug(const char* format, Args... args)
{
log(LogLevel::DEBUG, format, args...);
}
template<typename... Args>
void Logger::info(const char* format, Args... args)
{
log(LogLevel::INFO, format, args...);
}
template<typename... Args>
void Logger::warn(const char* format, Args... args)
{
log(LogLevel::WARN, format, args...);
}
template<typename... Args>
void Logger::error(const char* format, Args... args)
{
log(LogLevel::ERROR, format, args...);
}
std::string Logger::getCurrentTime() {
auto now = std::chrono::system_clock::now();
auto time_t = std::chrono::system_clock::to_time_t(now);