功能描述
打印调试信息到指定文件或当前终端,并自动加入时间戳。
传入参数
boot_time:0:墙上时间,1:系统启动时间
file:NULL:输出到当前终端,文件路径:输出到指定文件
代码实现
#include <time.h>
#include <stdarg.h>
#include <stdio.h>
static inline void my_dbg_write(int boot_time, const char *file, const char *fmt, ...)
{
va_list ap;
FILE *fp = NULL;
struct timespec ts;
if (file) {
fp = fopen(file, "a+");
if (!fp)
return ;
} else
fp = stderr;
clock_gettime(boot_time?CLOCK_MONOTONIC:CLOCK_REALTIME, &ts);
fprintf(fp, "[%s-%10ld.%09ld] ", boot_time?"boot":"real", ts.tv_sec, ts.tv_nsec);
va_start(ap, fmt);
vfprintf(fp, fmt, ap);
va_end(ap);
if (file)
fclose(fp);
return ;
}
#define MY_DBG_LOG(fmt, ...) my_dbg_write(0, NULL, fmt, ## __VA_ARGS__)
int main(int argc, char **argv)
{
while (1) {
MY_DBG_LOG("time=%ld\n", time(NULL));
sleep(1);
}
return 0;
}