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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值