Linux 打印可变参数日志
生活随笔
收集整理的這篇文章主要介紹了
Linux 打印可变参数日志
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
實現了傳輸進去的字符串所在的文檔,函數和行數顯示功能。
實現了將傳入的可變參數打印到日志功能。
#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; }輸出結果:
?
轉載于:https://www.cnblogs.com/wanghao-boke/p/11151526.html
總結
以上是生活随笔為你收集整理的Linux 打印可变参数日志的全部內容,希望文章能夠幫你解決所遇到的問題。