来来来, 一起写个比printf更详细的log api接口:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
#define DEBUG_LOG(...) debug_log("DEBUG", __TIME__, __FILE__, __FUNCTION__, __LINE__, __VA_ARGS__)
void debug_log(
const char *logLevel,
const char *time,
const char *file,
const char *func,
const int iLine,
const char *format ,...)
{
#include <stdarg.h>
static char output[10240]={0};
va_list arglst;
va_start(arglst,format);
vsnprintf(output,sizeof(output),format, arglst);
printf("[%s][%s][%s][%s][%d]:%s\n",time, logLevel, file, func, iLine, output);
va_end(arglst);
}
int main()
{
DEBUG_LOG("%s, ranking NO.%d", "You are so smart", 1);
return 0;
}
结果:
taoge@localhost Desktop> g++ test.cpp && ./a.out
[08:27:50][DEBUG][test.cpp][main][30]:You are so smart, ranking NO.1
有很多时候, 如上方法还是不太方便, 无法打印到终端, 那怎么办呢? 我们前面已经说过了, 用文件搞起(说明一下:如下频繁打开文件, 影响性能, 但程序主要是为了示意,在自己进行调试时, 可用就行):
#include <iostream>
#include <string>
#include <vector>
using namespace std;
#define DEBUG_LOG(...) debug_log("DEBUG", __TIME__, __FILE__, __FUNCTION__, __LINE__, __VA_ARGS__)
void debug_log(
const char *logLevel,
const char *time,
const char *file,
const char *func,
const int iLine,
const char *format ,...)
{
#include <stdarg.h>
static char output[10240]={0};
va_list arglst;
va_start(arglst,format);
vsnprintf(output,sizeof(output),format, arglst);
// 此处有频繁打开关闭文件哦
FILE *fp = fopen("/data/home/xxx/log.txt", "a+"); // 不检查fp, core了才好呢
fprintf(fp, "[%s][%s][%s][%s][%d]:%s\n",time, logLevel, file, func, iLine, output);
fclose(fp);
va_end(arglst);
}
int main()
{
DEBUG_LOG("%s, ranking NO.%d", "You are so smart", 1);
return 0;
}
结果, log确实打印到文件了。 在比较大型的工程中, 当方面工程中的log函数不起作用的时候, 我经常这么搞, 用自己的log api来调试。
最后说一下, 文件路径要对且有权限哦, 否则就会有core.