0
点赞
收藏
分享

微信扫一扫

Debug调试,保存的日志文件控制在2000行左右(可以当printf打印,也可以选择输出信息到文件,还能控制文件行数)


//Debug调试开关,打开则输出到文件,屏蔽则直接终端输出
//****************************************************
#define DEBUG //使能DEBUG,输出调试信息给文件
char *filepath="/opt/test.txt";
int max_rows=2000; //文件内容行数最大值
int file_rows=0; //实际文件内容行数
//****************************************************
//获取文件行数
int count( char *filename )
{
FILE *fp = fopen( filename, "r" );
int c, cnt = 0;
while( (c = fgetc( fp )) != EOF ) {
if ( c == '\n' ) {
cnt++;
}
}
fclose( fp );
return cnt;
}

void Dedug_printf(char *filepath, char *fmt, ...)
{
#ifdef DEBUG
file_rows=count(filepath);
if(file_rows>max_rows) //如果文件行数已经超过最大行数,则保留最后500行,最终文件内容会一直控制在500-2000行左右
{
system("tail -n 500 /opt/test.txt > /opt/test.tmp.bak");
system("rm /opt/test.txt");
system("mv /opt/test.tmp.bak /opt/test.txt");
}
FILE * fp;

va_list ap;
va_start(ap, fmt);

fp = fopen (filepath, "a+");

vfprintf(fp, fmt, ap);

fclose(fp);
va_end(ap);

#else
va_list args; //类似于printf
va_start(args, fmt);
vprintf(fmt, args);
va_end(args);
#endif
}

当printf使用:Dedug_printf(filepath, "%d",a);
输出到文件 #define DEBUG //使能DEBUG,输出调试信息给文件
Dedug_printf(filepath, "%d",a);


举报

相关推荐

0 条评论