Linux printf输出重定向及添加时间戳

Linux printf输出重定向及添加时间戳

代码

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <time.h>
#include <string.h>

FILE* fp = NULL;

char *get_cur_time()
{
    static char s[32] = {0};
    time_t t;
    struct tm* ltime;
    struct timeval stamp;
    gettimeofday(&stamp, NULL);
    ltime = localtime(&stamp.tv_sec);
    s[0] = '[';
    strftime(&s[1], 20, "%Y-%m-%d %H:%M:%S", ltime);
    sprintf(&s[strlen(s)], ".%03ld]", (stamp.tv_usec/1000));
    return s;
}

#define PRINT(tag, fmt, ...) printf("%s %s "fmt"\n", get_cur_time(), tag, ##__VA_ARGS__);fflush(fp)



int main(void)
{
	int i = 0;
    if(0 == (fp = freopen("./my.log", "a", stdout))) {
        printf("Cannot open file.\n");
    }
	while (1) {
		PRINT("log","hello world");
		usleep(100000);
	}
}

输出结果

编译执行以上代码,生成my.log文件,打开文件,如图:
在这里插入图片描述


版权声明:本文为poxioa原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。