实现了传输进去的字符串所在的文档,函数和行数显示功能。
实现了将传入的可变参数打印到日志功能。
1#include<stdio.h> 2#include<stdarg.h> 3#include<string.h> 4 5const char * g_path = "/home/exbot/wangqinghe/log.txt"; 6#define LOG(fmt,...) my_fprintf(__FILE__,__FUNCTION__,__LINE__,fmt,##__VA_ARGS__) 7 8int my_fprintf(const char *pFileName,const char *pFunName,const long lLine,const char* fmt,...) 9{ 10 printf("%s-%s-%d\n",__FILE__,__FUNCTION__,__LINE__); 11 int iRet = -1; 12 int i = 0; 13 va_list args; 14 va_start(args,fmt); 15 FILE* fp = NULL; 16 fp = fopen(g_path,"at+"); 17 18 int nFileNameLen = strlen(pFileName); 19 char szLine[10] = {0}; 20 sprintf(szLine,"%ld",lLine); 21 int nLineLen = strlen(szLine); 22 int nSpaceLen = 30 - nFileNameLen - nLineLen; 23 for(i = 0; i < nSpaceLen; ++i) 24 { 25 fwrite(" ",1,1,fp); 26 } 27 fprintf(fp,"%s:%ld ",pFileName,lLine); 28 iRet = vfprintf(fp,fmt,args); 29 printf("iRet = %d\n",iRet); 30 va_end(args); 31 fflush(fp); 32 fclose(fp); 33 return iRet; 34} 35 36 37int main() 38{ 39 char *p = "this is my first debug"; 40 printf("%s-%s-%d\n",__FILE__,__func__,__LINE__); 41 LOG("%s %d\n",p,1); 42 return 0; 43}
输出结果:
exbot@ubuntu:~/wangqinghe/C/20190703$ gcc log.c -o log
exbot@ubuntu:~/wangqinghe/C/20190703$ ./log
log.c-main-41
log.c-my_fprintf-10
iRet = 25
在/home/exbot/wangqinghe/log.txt中有如下输出结果:

简单化版:
1#include<stdio.h> 2#include<stdarg.h> 3#include<string.h> 4 5const char * g_path = "/home/exbot/wangqinghe/log.txt"; 6#define LOG(fmt,...) my_fprintf(__FILE__,__FUNCTION__,__LINE__,fmt,##__VA_ARGS__) 7 8int my_fprintf(const char *pFileName,const char *pFunName,const long lLine,const char* fmt,...) 9{ 10 printf("%s-%s-%d\n",__FILE__,__FUNCTION__,__LINE__); 11 int iRet = -1; 12 int i = 0; 13 va_list args; 14 va_start(args,fmt); 15 FILE* fp = NULL; 16 fp = fopen(g_path,"at+"); 17 fprintf(fp,"%s:%ld ",pFileName,lLine); 18 iRet = vfprintf(fp,fmt,args); //使用参数列表发送格式化输出到流stream中 19 printf("iRet = %d\n",iRet); 20 va_end(args); 21 fflush(fp); 22 fclose(fp); 23 return iRet; 24} 25 26 27int main() 28{ 29 char *p = "this is my first debug"; 30 printf("%s-%s-%d\n",__FILE__,__func__,__LINE__); 31 LOG("%s %d\n",p,1); 32 //getchar(); 33 return 0; 34}
输出结果:
