1. C/C++ 打印日志到文件示例代码
// LogPrint.cpp
#include <stdio.h>
#include <unistd.h>
#include <stdarg.h>
#include <string.h>
#include <fcntl.h>
#include <time.h>
#define MAX_LEN 1024
#define LOG_FILE "./Test.log"
FILE *fd_log = nullptr;
int Log_Init()
{
int ret = -1;
if( (fd_log = fopen(LOG_FILE, "a+")) == nullptr)
{
printf("open file failed!\n");
}
else {
printf("open file successed!\n");
ret = 0;
}
return ret;
}
void Log_End()
{
fclose(fd_log);
}
// 使用方法同 printf
void Log_Printf(const char *fmt, ...)
{
static bool print_time = true; //是否要打印时间: 当 debug_mode 为真,且上一次是换行符结尾。
char message[MAX_LEN];
// 当前时间.
time_t timer = time(NULL);
strftime(message, 24, "\n[%Y-%m-%d %H:%M:%S] ", localtime(&timer));
va_list args;
va_start(args, fmt);
vsnprintf(message + 23, MAX_LEN - 23, fmt, args);
va_end(args);
printf("%s\n", message + 23);
if (fwrite(message, strlen(message), 1, fd_log) != 1)
{
perror("lprintf");
}
}
int main()
{
printf("Begin -------------\n");
Log_Init();
Log_Printf("sssssssssssssssssssssssss2");
Log_Printf("222222222222222222222222222");
Log_Printf("122485444444444444444");
Log_End();
printf("End -------------\n");
}
2. 编译命令
g++ -std=c++17 LogPrint.cpp -o LogPrint
3. 运行结果
X:~/TestCode$ ./LogPrint
Begin -------------
open file successed!
sssssssssssssssssssssssss2
222222222222222222222222222
122485444444444444444
End -------------
X:~/TestCode$ cat Test.log
[2021-12-09 14:16:49] sssssssssssssssssssssssss2
[2021-12-09 14:16:49] 222222222222222222222222222
[2021-12-09 14:16:49] 122485444444444444444
4. 参考连接
打印并输出 log/日志到文件(C++)_mb60f8ef05632b9_51CTO博客