加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Linux > 正文

Linux 打印可变参数日志

发布时间:2020-12-13 22:43:26 所属栏目:Linux 来源:网络整理
导读:实现了传输进去的字符串所在的文档,函数和行数显示功能。 实现了将传入的可变参数打印到日志功能。 #includestdio.h #include stdarg.h #include string .h const char * g_path = " /home/exbot/wangqinghe/log.txt " ; #define LOG(fmt,...) my_fprintf(_

实现了传输进去的字符串所在的文档,函数和行数显示功能。

实现了将传入的可变参数打印到日志功能。

#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-%dn",__FILE__,__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,args);
    printf("iRet = %dn",iRet);
    va_end(args);
    fflush(fp);    
    fclose(fp);
    return iRet;
}


int main()
{
    char *p = "this is my first debug";
    printf("%s-%s-%dn",__func__,__LINE__);
    LOG("%s %dn",p,1);
    return 0;
}    

输出结果:

[email?protected]:~/wangqinghe/C/20190703$ gcc log.c -o log

[email?protected]:~/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,"at+");
    fprintf(fp,lLine);
    iRet = vfprintf(fp,args); //使用参数列表发送格式化输出到流stream中
    printf("iRet = %dn",1);
    //getchar();
    return 0;
}    

输出结果:

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读