• 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
    ",__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
    ",iRet);
        va_end(args);
        fflush(fp);    
        fclose(fp);
        return iRet;
    }
    
    
    int main()
    {
        char *p = "this is my first debug";
        printf("%s-%s-%d
    ",__FILE__,__func__,__LINE__);
        LOG("%s %d
    ",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
    ",__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
    ",iRet);
        va_end(args);
        fflush(fp);    
        fclose(fp);
        return iRet;
    }
    
    
    int main()
    {
        char *p = "this is my first debug";
        printf("%s-%s-%d
    ",__FILE__,__func__,__LINE__);
        LOG("%s %d
    ",p,1);
        //getchar();
        return 0;
    }    

    输出结果:

  • 相关阅读:
    DB2 字段操作
    解析二维码
    Eclipse tomcat 内存溢出
    hereim_美句_1
    js自定义函数默认参数的写法
    PHP和JS判断访问客户端的是PC还是移动设备
    lampp服务器配置httpd-vhosts.conf文件,设置多域名
    价值7000万的商业模式,羊毛出在狗身上,猪来买单
    确保 PHP 应用程序的安全
    美国淘金的故事
  • 原文地址:https://www.cnblogs.com/wanghao-boke/p/11151526.html
Copyright © 2020-2023  润新知