我正在实现一个日志函数,它会记录代码的行号。代码片段如下:
#include <iostream>
using namespace std;
char m_buffer[500];
template<typename... Args>
void format_buffer(int line, const char* logData, Args... args)
{
snprintf(m_buffer, 500, logData, line, args...);
cout << m_buffer << endl;
}
template<int line = __builtin_LINE(), typename... Args>
void log_error(const char* logData, Args... args)
{
format_buffer(line, logData, args...);
}
int main()
{
float f1 = 12.35f;
log_error("Line %d: Sample error, signal value is %f",f1);
return 0;
}
这里,输出如下: 第15行:样本错误,信号值为12.350000 此处打印模板函数的行号,但不打印日志语句。
我尝试使用LINE宏,如下所示:
#include <iostream>
using namespace std;
char m_buffer[500];
template<typename... Args>
void format_buffer(int line, const char* logData, Args... args)
{
snprintf(m_buffer, 500, logData, line, args...);
cout << m_buffer << endl;
}
template<typename... Args>
void log_error(int line, const char* logData, Args... args)
{
format_buffer(line, logData, args...);
}
int main()
{
float f1 = 12.35f;
log_error(__LINE__, "Line %d: Sample error, signal value is %f",f1);
return 0;
}
输出为: 第24行:样本错误,信号值为12.350000 行号打印为日志语句。 我担心的是我不希望用户在每个日志语句中使用 LINE 宏,而是想从 API 中获取行号。事实上,我不希望我的函数对如下所示的行使用格式说明符。
log_error("Line %d: Sample error, signal value is %f",f1);
我希望用户使用如下:
log_error("Sample error, signal value is %f",f1);
自动打印行号。
是否可以在用户不指定宏的情况下获取日志语句的行号?
注意:我使用的是c++14编译器。
为了快速修复,您可以使用宏:
template <int line, class... Args>
void log_error(const char* logData, Args... args) {
format_buffer(line, logData, args...);
}
#define LOG_ERROR(...) log_error<__LINE__>(__VA_ARGS__)
int main() {
float f1 = 12.35f;
LOG_ERROR("Line %d: Sample error, signal value is %f", f1);
return 0;
}
boost::source_location
,自 C++20 起,它已作为 std::source_location
包含在标准库中。