Linux 打印可变参数日志
2024-09-01 03:34:04
实现了传输进去的字符串所在的文档,函数和行数显示功能。
实现了将传入的可变参数打印到日志功能。
#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 = -;
int i = ;
va_list args;
va_start(args,fmt);
FILE* fp = NULL;
fp = fopen(g_path,"at+"); int nFileNameLen = strlen(pFileName);
char szLine[] = {};
sprintf(szLine,"%ld",lLine);
int nLineLen = strlen(szLine);
int nSpaceLen = - nFileNameLen - nLineLen;
for(i = ; i < nSpaceLen; ++i)
{
fwrite(" ",,,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,);
return ;
}
输出结果:
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 = -;
int i = ;
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,);
//getchar();
return ;
}
输出结果:
最新文章
- 6-tips-for-managing-property-files-with-spring--转
- Apache与Nginx虚拟主机设置(多域名和多端口的区别)
- 【控件扩展】带圆角、边框、渐变的panel
- C#dll中无法找到c++dll中函数的入口
- 通过email分享
- 111_leetcode_Best Time to Buy and Sell Stock III
- servletConfig对象
- jquery实现图片切换和js实现图片切换
- js中的|| 与 &;&;
- Spring + mybatis整合方案总结 结合实例应用
- C. Table Decorations(Codeforces Round 273)
- String的构造函数、析构函数和赋值函数
- phpstorm9整合本地apache和豆沙绿主题设置(附资源)
- KMP算法讲解
- DVA框架统一处理所有页面的loading状态
- Error处理:Unable to execute dex: java.nio.BufferOverflowException. Check the Eclipse log for stack tra
- IIS8的SNI功能实现同一服务器多HTTPS站点
- 插播一则关于HTTP Headers详解~~~
- mysql批量查询
- [Oracle]使用InstantClient访问Oracle数据库