实现了传输进去的字符串所在的文档,函数和行数显示功能。
实现了将传入的可变参数打印到日志功能。
#include<stdio.h>
#include<stdarg.h>
#include<string.h>
const char * g_path = "/home/exbot/wangqinghe/log.txt";
#define LOG(fmt,...) my_fprintf(__FILE__,__FUNCTION__,__LINE__,fmt,##__VA_ARGS__)
int my_fprintf(const char *pFileName,const char *pFunName,const long lLine,const char* fmt,...)
{
printf("%s-%s-%d\n",__FILE__,__FUNCTION__,__LINE__);
int iRet = -1;
int i = 0;
va_list args;
va_start(args,fmt);
FILE* fp = NULL;
fp = fopen(g_path,"at+");
int nFileNameLen = strlen(pFileName);
char szLine[10] = {0};
sprintf(szLine,"%ld",lLine);
int nLineLen = strlen(szLine);
int nSpaceLen = 30 - nFileNameLen - nLineLen;
for(i = 0; i < nSpaceLen; ++i)
{
fwrite(" ",1,1,fp);
}
fprintf(fp,"%s:%ld ",pFileName,lLine);
iRet = vfprintf(fp,fmt,args);
printf("iRet = %d\n",iRet);
va_end(args);
fflush(fp);
fclose(fp);
return iRet;
}
int main()
{
char *p = "this is my first debug";
printf("%s-%s-%d\n",__FILE__,__func__,__LINE__);
LOG("%s %d\n",p,1);
return 0;
}
输出结果:
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中有如下输出结果:
简单化版:
#include<stdio.h>
#include<stdarg.h>
#include<string.h>
const char * g_path = "/home/exbot/wangqinghe/log.txt";
#define LOG(fmt,...) my_fprintf(__FILE__,__FUNCTION__,__LINE__,fmt,##__VA_ARGS__)
int my_fprintf(const char *pFileName,const char *pFunName,const long lLine,const char* fmt,...)
{
printf("%s-%s-%d\n",__FILE__,__FUNCTION__,__LINE__);
int iRet = -1;
int i = 0;
va_list args;
va_start(args,fmt);
FILE* fp = NULL;
fp = fopen(g_path,"at+");
fprintf(fp,"%s:%ld ",pFileName,lLine);
iRet = vfprintf(fp,fmt,args); //使用参数列表发送格式化输出到流stream中
printf("iRet = %d\n",iRet);
va_end(args);
fflush(fp);
fclose(fp);
return iRet;
}
int main()
{
char *p = "this is my first debug";
printf("%s-%s-%d\n",__FILE__,__func__,__LINE__);
LOG("%s %d\n",p,1);
//getchar();
return 0;
}
输出结果: