Since I'd like not to do code repetition here, I'm trying to figure out a way to move the common part for each of these logger functions (e.g. debug, warning, info, etc.) into another single function.
I've tried a naive approach myself but doesn't seem to be working properly. I suppose I need to pass a va_list
directly but in doing that I don't know if it's worth it to create a separate function in the first place anymore. Any ideas/suggestions on how to achieve this?
Original
void ConsoleLogger::debug(const char *fmt...)
{
if (static_cast<uint8_t>(LogLevel::DEBUG) <= static_cast<uint8_t>(configuration.priority))
{
va_list args;
char log_text[LOG_MAX_LENGTH];
va_start(args, fmt);
vsnprintf(log_text, LOG_MAX_LENGTH, fmt, args);
va_end(args);
std::cout << get_time_as_string() + " [DEBUG] " + log_text + "\n";
std::cout.flush();
}
}
My shot which is not working as expected since the log_text gets populated with wrong/random characters while in the original it prints the correct string.
const std::string Logger::get_log_text(const char *fmt...) const
{
va_list args;
char log_text[LOG_MAX_LENGTH];
va_start(args, fmt);
vsnprintf(log_text, LOG_MAX_LENGTH, fmt, args);
va_end(args);
return std::string(log_text);
}
void ConsoleLogger::debug(const char *fmt...)
{
if (static_cast<uint8_t>(LogLevel::DEBUG) <= static_cast<uint8_t>(configuration.priority))
{
std::string log_text = get_log_text(fmt);
std::cout << get_time_as_string() + " [DEBUG] " + log_text + "\n";
std::cout.flush();
}
}